struct A {
A(int) : i(new int(783)) {
std::cout << "a ctor" << std::endl;
}
A(const A& other) : i(new int(*(other.i))) {
std::cout << "a copy ctor" << std::endl;
}
~A() {
std::cout << "a dtor" << std::endl;
delete i;
}
void get() {
std::cout << *i << std::endl;
}
private:
int* i;
};
const A& foo() {
return A(32);
}
const A& foo_2() {
return 6;
}
int main()
{
A a = foo();
a.get();
}
I know that returning references to local values is bad. But, on the other hand, a constant reference should extend the temporary lifetime of an object.
This code creates UB output. So no life extension.
Why? I mean, can someone explain what is going on step by step?
Where is the error in my logical chain?
Foo ():
A (32) - ctor
return A (32) - creates a const reference to the local object and returns
A a = foo (); - a is initialized with the return value foo (), the return value goes beyond the scope (outside the expression) and is destroyed, but a is already initialized;
(But actually, the destructor is called before the copy constructor)
foo_2 ():
( )