从 unique_ptr 移动到堆栈变量

Tou*_*dou 1 c++ unique-ptr move-semantics

是否可以T从 a 创建堆栈变量(具有移动构造函数的类型)std::unique_ptr<T>

我尝试过类似的东西

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
Run Code Online (Sandbox Code Playgroud)

但它看起来很难看,并且显然会造成内存泄漏。但不知道为什么。

Bot*_*tje 7

这是内存泄漏,因为您已将分配的内存与 unique_ptr 解耦,但它仍然被分配。假设您有一个正常运行的移动构造函数,为什么不:

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.
Run Code Online (Sandbox Code Playgroud)