R.31:如果需要实现标准库以外的智能指针,遵照标准库中的基本模式
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:
重载了一元*和->的任何类型(包括主要的模板和特化)都可以看作智能指针。
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
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!