下面的代码会导致段错误吗?
struct Dim {
int x, y, z;
};
Dim set_dim(int a) {
Dim l;
l.x=a;
l.y=a;
l.z=a;
return l;
}
int sum(const Dim &m) {
int s=m.x+m.y;
return s;
}
main() {
cout<<sum(set_dim(5))<<endl;
}
我认为可以,因为在 set_dim 中引用了局部变量“l”,换句话说,引用了现在超出范围的变量。但它的作用丝毫不减
最佳答案
这是明确定义的。 set_dim
按值返回,所以它返回的对象是局部变量l
的临时拷贝.然后将此临时绑定(bind)到 const
sum
的引用参数.这会影响临时对象的生命周期:
A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
因此临时对象的生命周期是完整表达式 cout<<sum(set_dim(5))<<endl;
. sum
时它仍然存在正在执行。
关于c++ - 没有段错误为什么?返回的函数值用作参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132252/