标签:c c11 shared-ptr unique-ptr
C 11标准库是否提供了从std :: shared_ptr转换为std :: unique_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 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转换为std :: shared_ptr,但不能将std :: shared_ptr转换为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,c11,shared-ptr,unique-ptr 来源: https://codeday.me/bug/20190930/1834708.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。