Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a temporary unique_ptr

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.

like image 797
Kam Avatar asked Jun 16 '15 04:06

Kam


People also ask

How do you dereference a unique pointer?

The unique_ptr shall not be empty (i.e., its stored pointer shall not be a null pointer) in order to be dereferenciable. This can easily be checked by casting the unique_ptr object to bool (see unique_ptr::operator bool). It is equivalent to: *get().

Can you move a unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

What happens when unique_ptr goes out of scope?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Can you delete a unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.


1 Answers

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.

like image 169
masoud Avatar answered Sep 29 '22 10:09

masoud