C++核心準則R.21:不需要共享所有權(quán)時應該使用unique_ptr而不是?s...

R.21: Prefer?unique_ptr?over?shared_ptr?unless you need to share ownership
R.21:不需要共享所有權(quán)時應該使用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從概念上更簡單,動作更加可預見(你知道析構(gòu)動作什么時候發(fā)生)而且更快(不需要隱式維護使用計數(shù))。
Example, bad(反面示例)
This needlessly adds and maintains a reference count.
不必要地增加和維護參照計數(shù)。
void f()
{
shared_ptr base = make_shared();
// use base locally, without copying it -- refcount never exceeds 1
} // destroy base
Example(示例)
This is more efficient:
下面的代碼更高效:
void f()
{
unique_ptr base = make_unique();
// 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.
(簡單)如果函數(shù)使用shared_ptr管理其內(nèi)局部分配的對象,但是從來沒有返回該智能指針或者將其傳遞個一個需要shared_ptr&的函數(shù),發(fā)出警告。建議使用unique_ptr。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r21-prefer-unique_ptr-over-shared_ptr-unless-you-need-to-share-ownership
覺得本文有幫助?請分享給更多人。
關注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
