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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With