unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
This code compiles but rA
contains garbage. Can someone explain to me why is this code invalid?
Note: if I assign the return of myFun
to a named unique_ptr
variable before dereferencing it, it works fine.
The
unique_ptr
will pass the ownership to anotherunique_ptr
, but in your code there is nothing to capture the ownership from the returning pointer. In other words, It can not transfer the ownership, so it will be destructed. The proper way is:or
In your code, the returning pointer will be desructed and the reference is refering to an object which is destructing soon, after that using this reference invokes an undefined behavior.