C ++ 11 unique_ptr和shared_ptr是否能够转换为彼此的类型? [英] Does C++11 unique_ptr and shared_ptr able to convert to each other's type?

查看:432
本文介绍了C ++ 11 unique_ptr和shared_ptr是否能够转换为彼此的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11标准库是否提供任何实用程序来将 std :: shared_ptr 转换为 std :: unique_ptr ,反之亦然?这样安全吗?

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?

推荐答案


std :: unique_ptr 是表示专有所有权的C ++ 11方法,但是它的
最吸引人的功能之一是它可以轻松有效地转换为 std :: shared_ptr

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 a std::shared_ptr.

这是为什么 std :: unique_ptr 非常适合作为工厂的一个关键部分函数返回类型。工厂函数无法知道调用者是否要对返回的对象使用专有所有权语义,或者共享所有权(即 std :: shared_ptr )是否更合适。通过返回 std :: unique_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 a std::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 std :: unique_ptr 是不允许的。将资源的生命周期管理转移到 std :: shared_ptr 之后,您将不会改变主意。即使引用计数为1,也无法收回资源所有权,例如要让 std :: unique_ptr 对其进行管理。

std::shared_ptr to std::unique_ptr is not allowed. Once you’ve turned lifetime management of a resource over to a std::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 a std::unique_ptr manage it.

参考:有效的现代C ++。改善您对C ++ 11和C ++ 14的使用的42种特定方法。斯科特·迈耶斯(Scott Meyers)。

Reference: Effective Modern C++. 42 SPECIFIC WAYS TO IMPROVE YOUR USE OF C++11 AND C++14. Scott Meyers.

简而言之,您可以轻松高效地转换 std :: unique_ptr std :: shared_ptr ,但是您不能将 std :: shared_ptr 转换为 std :: unique_ptr

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.

例如:

std::unique_ptr<std::string> unique = std::make_unique<std::string>("test");
std::shared_ptr<std::string> shared = std::move(unique);

或:

std::shared_ptr<std::string> shared = std::make_unique<std::string>("test");

这篇关于C ++ 11 unique_ptr和shared_ptr是否能够转换为彼此的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆