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?