Home > OS >  move from unique_ptr to stack variable
move from unique_ptr to stack variable

Time:11-20

Is it possible to create a stack variable (of type T with a move constructor) from a std::unique_ptr<T>?

I tried something like

std::unique_ptr<T> p = ext_get_my_pointer();   // external call returns a smart pointer
T val{std::move(*p.release())};                // I actually need a stack variable

but it looks ugly, and creates a memory leak apparently. Not sure why though.

CodePudding user response:

It is a memory leak because you have decoupled the allocated memory from the unique_ptr, but it is still allocated. Assuming you have a functioning move constructor, why not:

std::unique_ptr<T> p = ext_get_my_pointer(); 
T val{std::move(*p)};
// p goes out of scope so is freed at the end of the block, or you can call `p.reset()` explicitly.

CodePudding user response:

Yes, it creates a memory leak, because with p.release() you say that you take responsibility for the object, and due to that you need to delete it.

You would do something like this:

std::unique_ptr<T> p = ext_get_my_pointer();   // external call returns a smart pointer
T val{std::move(*p)};
p.reset(nullptr);
  • Related