19
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.

3
  • 2
    Since you are not storing the unique_ptr that myFun returns, its destructor is called at the end of the expression, and the object it owned is freed.
    – user703016
    Jun 16, 2015 at 4:35
  • @buttifulbuttefly I saw that in the dessasembly, I don't understand how is the destructor call triggered.
    – Kam
    Jun 16, 2015 at 4:36
  • 12
    As seen on TV
    – Kerrek SB
    Sep 28, 2015 at 21:07

2 Answers 2

14

The unique_ptr will pass the ownership to another unique_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:

unique_ptr<A> rA = myFun(); // Pass the ownership

or

const A rA = *myFun(); // Store the values before destruction

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.

0
7
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.

2
  • I am a bit confused. What is unique_ptr<A>*, a raw pointer points to a unique_ptr? myFun doesn't take any arguments, why is myFun(&temporary) valid?
    – Milo Lu
    Feb 6, 2016 at 23:22
  • @MiloLu : It's pseudocode demonstrating the lifetime of myFun's return value.
    – ildjarn
    Feb 8, 2016 at 0:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.