简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM