unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
What you did on that last line:
unique_ptr<A>* temporary = new unique_ptr<A>(nullptr);
myFun(&temporary);
const A& rA = *temporary.get();
delete temporary; // and free *temporary
When you delete temporary
it has a contract with you that it owns the pointer and the memory that refers to. So it destructs the A
and frees the memory.
Meanwhile, you've sneakily kept a pointer to that memory as a reference to the object at that address.
You could either transfer the pointer to a local unique_ptr:
unique_ptr<A> a = myFun();
or you could copy the objects:
A = *myFun().get();
The 'A' to which myFun()
s temporary is only destructed at the close of the statement, so it's present for the copy.
unique_ptr
thatmyFun
returns, its destructor is called at the end of the expression, and the object it owned is freed.