我有一些关于从函数返回对局部变量的引用的问题:
class A {
public:
A(int xx)
: x(xx)
{
printf("A::A()\n");
}
};
const A& getA1()
{
A a(5);
return a;
}
A& getA2()
{
A a(5);
return a;
}
A getA3()
{
A a(5);
return a;
}
int main()
{
const A& newA1 = getA1(); //1
A& newA2 = getA2(); //2
A& newA3 = getA3(); //3
}
我的问题是 =>
getA1()
的实现是否正确? 我觉得这是不正确的,因为它返回的是局部变量或临时变量的地址。main
(1,2,3) 中的哪些语句会导致未定义的行为?在
const A& newA1 = getA1();
中,标准是否保证 const 引用的临时绑定(bind)在引用超出范围之前不会被销毁?
最佳答案
1. Is
getA1()
implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary.
getAx()
在您的程序中唯一正确的版本是 getA3()
。无论您以后如何使用它们,其他两个都有未定义的行为。
2. Which of the statements in main ( 1,2,3) will lead to undefined behavior ?
从某种意义上说,它们都不是。对于 1 和 2,未定义的行为是函数体的结果。对于最后一行,newA3
应该是编译错误,因为您不能将临时对象绑定(bind)到非 const 引用。
3. In
const A& newA1 = getA1();
does standard guarantees that temporary bound by aconst
reference will not be destroyed until the reference goes out of scope?
没有。下面是一个例子:
A const & newConstA3 = getA3 ();
这里,getA3()
返回一个临时对象,该临时对象的生命周期现在绑定(bind)到对象 newConstA3
。换句话说,临时文件将一直存在,直到 newConstA3
超出范围。
关于c++ - 从函数返回对局部变量的 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465851/