struct A {
A(int) : i(new int(783)) {
std::cout << \"a ctor\" << std::endl;
}
A(const A& other) : i(new int(*(other.i))) {
You are misinterpeting "until function exit". If you really want to use a const reference to extend the life of an object beyond foo
, use
A foo() {
return A(32);
}
int main() {
const A& a = foo();
}
You must return from foo
by value, and then use a const reference to reference the return value, if you wish to extend things in the way you expect.
As @AndreyT has said, the object is destroyed in the function that has the const &
. You want your object to survive beyond foo
, and hence you should not have const &
(or &
) anywhere in foo
or in the return type of foo
. The first mention of const &
should be in main
, as that is the function that should keep the object alive.
You might think this return-by-value code is slow as there appear to be copies of A made in the return, but this is incorrect. In most cases, the compiler can construct A only once, in its final location (i.e. on the stack of the calling function), and then set up the relevant reference.