R.21: Prefer unique_ptr over shared_ptr unless you need to share ownership

R.21:不需要共享所有权时应该使用unique_ptr而不是shared_ptr

Reason(原因)

A unique_ptr is conceptually simpler and more predictable (you know when destruction happens) and faster (you don't implicitly maintain a use count).

unique_ptr从概念上更简单,动作更加可预见(你知道析构动作什么时候发生)而且更快(不需要隐式维护使用计数)。

 

Example, bad(反面示例)

This needlessly adds and maintains a reference count.

不必要地增加和维护参照计数。

void f()
{
shared_ptr<Base> base = make_shared<Derived>();
// use base locally, without copying it -- refcount never exceeds 1
} // destroy base

Example(示例)

This is more efficient:

下面的代码更高效:

void f()
{
unique_ptr<Base> base = make_unique<Derived>();
// use base locally
} // destroy base

 

Enforcement(实施建议)

(Simple) Warn if a function uses a Shared_pointer with an object allocated within the function, but never returns the Shared_pointer or passes it to a function requiring a Shared_pointer&. Suggest using unique_ptr instead.

(简单)如果函数使用shared_ptr管理其内局部分配的对象,但是从来没有返回该智能指针或者将其传递个一个需要shared_ptr&的函数,发出警告。建议使用unique_ptr。

 

原文链接

​https:///isocpp/CppCoreGuidelines/blob/master/#r21-prefer-unique_ptr-over-shared_ptr-unless-you-need-to-share-ownership​


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】