前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.31:如果需要实现标准库以外的智能指针,遵照标准库中的基本模式​

C++核心准则R.31:如果需要实现标准库以外的智能指针,遵照标准库中的基本模式​

作者头像
面向对象思考
发布2020-04-14 16:46:55
3800
发布2020-04-14 16:46:55
举报

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(示例)

代码语言:javascript
复制
// 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


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • R.31: If you have non-std smart pointers, follow the basic pattern from std
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档