C++核心準則R.21:不需要共享所有權時使用獨佔指針而非共享指針

C++核心準則R.21:不需要共享所有權時使用獨佔指針而非共享指針

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.

不必要地增加和維護參照計數。

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

Example(示例)

This is more efficient:

下面的代碼更高效:

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

​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


覺得本文有幫助?請分享給更多人。

關注【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!


分享到:


相關文章: