C++核心準則R.22: 使用make_shared()構建共享shared_ptr

R.22: Use make_shared() to make shared_ptrs

R.22: 使用make_shared()構建共享shared_ptr

 

Reason(原因)

If you first make an object and then give it to a shared_ptr constructor, you (most likely) do one more allocation (and later deallocation) than if you use make_shared() because the reference counts must be allocated separately from the object.

如果你首先構建一個對象然後將它交給shared_ptr的構造函數,和使用make_shared的情況相比,你(很有可能)多執行了一次分配動作(和將要發生的一次釋放動作)。因爲參照計數(此處應該是shared_ptr對象,譯者注)的分配必須和對象的分配分別進行。

 

Example(示例)

Consider(考慮下面的代碼):

 

shared_ptr<X> p1 { new X{2} }; // bad
auto p = make_shared<X>(2);    // good

The make_shared() version mentions X only once, so it is usually shorter (as well as faster) than the version with the explicit new.

make_shared方式只是用一次X對象,因此它通常比顯式調用new的代碼更簡短(執行也更高效)。

 

Enforcement(實施建議)

(Simple) Warn if a shared_ptr is constructed from the result of new rather than make_shared.

(簡單)如果使用new的結果構造shared_ptr而不是make_shared,報警。

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r22-use-make_shared-to-make-shared_ptrs


 

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

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

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