C ++ 11 unique_ptr 和 shared_ptr 是否能够转换为彼此的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37884728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does C++11 unique_ptr and shared_ptr able to convert to each other's type?
提问by Hind Forsum
Does C++11 standard library provide any utility to convert from a std::shared_ptr
to std::unique_ptr
, or vice versa? Is this safe operation?
C++11 标准库是否提供任何实用程序来从 a 转换std::shared_ptr
为std::unique_ptr
,反之亦然?这是安全操作吗?
回答by chema989
std::unique_ptr
is the C++11 way to express exclusive ownership, but one of its most attractive features is that it easily and efficiently converts to astd::shared_ptr
.This is a key part of why
std::unique_ptr
is so well suited as a factory function return type. Factory functions can't know whether callers will want to use exclusive ownership semantics for the object they return or whether shared ownership (i.e.,std::shared_ptr
) would be more appropriate. By returning astd::unique_ptr
, factories provide callers with the most efficient smart pointer, but they don't hinder callers from replacing it with its more flexible sibling.
std::shared_ptr
tostd::unique_ptr
is not allowed. Once you've turned lifetime management of a resource over to astd::shared_ptr
, there's no changing your mind. Even if the reference count is one, you can't reclaim ownership of the resource in order to, say, have astd::unique_ptr
manage it.Reference: Effective Modern C++. 42 SPECIFIC WAYS TO IMPROVE YOUR USE OF C++11 AND C++14. Scott Meyers.
std::unique_ptr
是 C++11 表达独占所有权的方式,但它最吸引人的特性之一是它可以轻松有效地转换为std::shared_ptr
.这是为什么
std::unique_ptr
非常适合作为工厂函数返回类型的关键部分。工厂函数无法知道调用者是否希望对他们返回的对象使用独占所有权语义,或者共享所有权(即std::shared_ptr
)是否更合适。通过返回 astd::unique_ptr
,工厂为调用者提供了最有效的智能指针,但它们不会阻止调用者用更灵活的兄弟替换它。
std::shared_ptr
到std::unique_ptr
是不允许的。一旦您将资源的生命周期管理转变为std::shared_ptr
,您的想法就不会改变。即使引用计数为 1,您也无法收回资源的所有权以进行std::unique_ptr
管理。参考:有效的现代 C++。改进 C++11 和 C++14 使用的 42 种特定方法。斯科特·迈耶斯。
In short, you can easily and efficiently convert a std::unique_ptr
to std::shared_ptr
but you cannot convert std::shared_ptr
to std::unique_ptr
.
简而言之,您可以轻松有效地将 a 转换为std::unique_ptr
,std::shared_ptr
但不能转换std::shared_ptr
为std::unique_ptr
.
For example:
例如:
std::unique_ptr<std::string> unique = std::make_unique<std::string>("test");
std::shared_ptr<std::string> shared = std::move(unique);
or:
或者:
std::shared_ptr<std::string> shared = std::make_unique<std::string>("test");
回答by nmr
Given unique_ptr u_ptr, create shared_ptr s_ptr:
给定 unique_ptr u_ptr,创建 shared_ptr s_ptr:
std::shared_ptr<whatever> s_ptr(u_ptr.release());
Going the other way is impractical.
走另一条路是不切实际的。