C++核心準則R.21:不需要共享所有權時應該使用unique_ptr而不是 shared_ptr

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://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r21-prefer-unique_ptr-over-shared_ptr-unless-you-need-to-share-ownership


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章