问题描述
struct test{
char c_arr[1];
};
test array[1] = g++
;
test get(int index){
return array[index];
}
int main(){
char* a = get(0).c_arr;
return 0;
}
使用 clang++
编译没有警告,但使用 warning: temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression
会打印以下内容:
get(0).c_arr
这是错误的吗? get(0)
不返回指向全局数组的指针吗?
还是 c_arr
返回一个临时变量并且编译器错误地认为 void call(char* in){}
int main(){
call(get(0).c_arr);
return 0;
}
只是它的一个实例,而不是全局变量?
编辑
为什么将这个临时变量传递给函数没有警告?
Book(ISBN,Name,Genre)
Details(ISBN,Price,Total_pages)
解决方法
UIView paddingView = new UIView(new CGRect(0,iconSize.Width + 8,iconSize.Height + 8));
UIImageView sideView = new UIImageView(new CGRect(0,4,iconSize.Width,iconSize.Height));
sideView.Image = downarrow;
paddingView.AddSubview(sideView);
paddingView.UserInteractionEnabled = true;
_dateLabel.RightViewMode = UITextFieldViewMode.Always;
_dateLabel.RightView = paddingView;
//add this
sideView.UserInteractionEnabled = true;
UITapGestureRecognizer tap = new UITapGestureRecognizer(()=> {
_dateLabel.BecomeFirstResponder();
});
paddingView.AddGestureRecognizer(tap);
返回按值,然后 get
确实返回一个临时对象,该临时对象在完整表达式之后被销毁,左 get(0)
是一个悬空指针。
请注意,返回的临时 a
是从 test
复制的,包括数组数据成员 array[index]
。 c_arr
应该指向临时 a
的数据成员数组 c_arr
的第一个元素,在完整表达式之后(即 test
中的 ;
) 整个临时 char* a = get(0).c_arr;
(及其数据成员 test
)被销毁,然后 c_arr
变为悬空。
如果 a
按引用返回,那就没问题了。
get
编辑
您添加的代码没问题。临时在完整表达式之后销毁,即在 test& get(int index){
return array[index];
}
中的 ;
之后。传递给 call(get(0).c_arr);
的指针在 call
内仍然有效。