从函数返回const引用到局部变量 [英] Returning const reference to local variable from a function
问题描述
对于从函数返回对局部变量的引用,我有一些问题:
class A
{
public:
A(int xx):x(xx)
{
printf(A :: A()\\\
);
}
};
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()
的实现是否正确?
我觉得它不正确,因为它返回一个局部变量或临时的地址。 -
1。是
getA1()
实现是否正确?我觉得它是不正确的,因为它返回的本地变量或临时的地址。
程序中正确的 getAx()
getA3()
。两个人都有未定义的行为,无论你以后如何使用它们。
2。 main(1,2,3)中的哪个语句会导致未定义的行为?
对于1和2,未定义的行为是函数体的结果。对于最后一行, newA3
应该是一个编译错误,因为您无法将临时对象绑定到非常量引用。
3。在
const A& newA1 = getA1();
确保标准保证临时由const
引用绑定不会被销毁,直到引用出去范围?
否。下面是一个例子:
A const& newConstA3 = getA3();
这里, getA3()
并且该临时的生命周期现在绑定到对象 newConstA3
。换句话说,临时将存在,直到 newConstA3
超出范围。
I have some questions on returning a reference to a local variable from a function:
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
}
My questions are =>
Is the implementation of
getA1()
correct? I feel it is incorrect as it is returning the address of a local variable or temporary.Which of the statements in
main
(1,2,3) will lead to undefined behavior?In
const A& newA1 = getA1();
does the standard guarantee that a temporary bound by a const reference will not be destroyed until the reference goes out of scope?
1. Is
getA1()
implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary.
The only version of getAx()
that is correct in your program is getA3()
. Both of the others have undefined behaviour no matter how you use them later.
2. Which of the statements in main ( 1,2,3) will lead to undefined behavior ?
In one sense none of them. For 1 and 2 the undefined behaviour is as a result of the bodies of the functions. For the last line, newA3
should be a compile error as you cannot bind a temporary to a non const reference.
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?
No. The following is an example of that:
A const & newConstA3 = getA3 ();
Here, getA3()
returns a temporary and the lifetime of that temporary is now bound to the object newConstA3
. In other words the temporary will exist until newConstA3
goes out of scope.
这篇关于从函数返回const引用到局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!