C++核心準則R.31:如果需要實現標準庫以外的智能指針,遵照標準庫中的基本模式

R.31: If you have non-std smart pointers, follow the basic pattern from std

R.31:如果需要實現標準庫以外的智能指針,遵照標準庫中的基本模式

 

Reason(原因)

The rules in the following section also work for other kinds of third-party and custom smart pointers and are very useful for diagnosing common smart pointer errors that cause performance and correctness problems. You want the rules to work on all the smart pointers you use.

後面章節中的準則也適用於其他類型的第三方和自定義的智能指針,它們對於發現一般的可能導致性能和正確性問題的智能指針錯誤很有效。你需要的是對所有智能指針都有效的的準則。

Any type (including primary template or specialization) that overloads unary * and -> is considered a smart pointer:

重載了一元*和->的任何類型(包括主要的模板和特化)都可以看作智能指針。

  • If it is copyable, it is recognized as a reference counted shared_ptr.

  • 如果它是可拷貝的,就被認爲是帶有參照計數的共享指針。

  • If it is not copyable, it is recognized as a unique unique_ptr.

  • 如果它不可拷貝,就被認爲是獨佔的unique_ptr。

     

     

Example(示例)

// use Boost's intrusive_ptr
#include <boost/intrusive_ptr.hpp>
void f(boost::intrusive_ptr<widget> p)  // error under rule 'sharedptrparam'
{
    p->foo();
}

// use Microsoft's CComPtr
#include <atlbase.h>
void f(CComPtr<widget> p)               // error under rule 'sharedptrparam'
{
    p->foo();
}

Both cases are an error under the sharedptrparam guideline: p is a Shared_pointer, but nothing about its sharedness is used here and passing it by value is a silent pessimization; these functions should accept a smart pointer only if they need to participate in the widget's lifetime management. Otherwise they should accept a widget*, if it can be nullptr. Otherwise, and ideally, the function should accept a widget&. These smart pointers match the Shared_pointer concept, so these guideline enforcement rules work on them out of the box and expose this common pessimization.

兩種情況都犯了sharedptrParam準則指出的錯誤:p是一個共享指針,但是這裏沒有用到任何有關共享的功能。而且通過傳值方式傳遞智能指針是一種默認的許可;這個函數應該只在參與widget的生命週期管理時才接受智能指針。其他情況下:如果函數允許爲空,它們應該接受widget*,否則應該接受widget&。這些智能指針匹配Shared_pointer概念,因此推薦這些準則推薦的規則也可以馬上適用於它們。

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r31-if-you-have-non-std-smart-pointers-follow-the-basic-pattern-from-std

 


 

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

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

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