Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move from unique_ptr to stack variable

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.

like image 937
Touloudou Avatar asked May 08 '26 06:05

Touloudou


2 Answers

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.
like image 68
Botje Avatar answered May 09 '26 19:05

Botje


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);
like image 41
t.niese Avatar answered May 09 '26 19:05

t.niese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!