[英]move from unique_ptr to stack variable
是否可以从std::unique_ptr<T>
创建堆栈变量(具有移动构造函数的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
但它看起来很难看,并且显然会产生 memory 泄漏。 不知道为什么。
这是一个 memory 泄漏,因为您已将分配的 memory 与 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.
是的,它会造成 memory 泄漏,因为使用p.release()
你说你对 object 负责,因此你需要delete
它。
你会做这样的事情:
std::unique_ptr<T> p = ext_get_my_pointer(); // external call returns a smart pointer
T val{std::move(*p)};
p.reset(nullptr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.