前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则R.2: 只在接口中表示单独对象使用原始指针​

C++核心准则R.2: 只在接口中表示单独对象使用原始指针​

作者头像
面向对象思考
发布2020-03-25 17:05:55
4380
发布2020-03-25 17:05:55
举报
文章被收录于专栏:C++核心准则原文翻译

R.2: In interfaces, use raw pointers to denote individual objects (only)

R.2: 只在接口中表示单独对象使用原始指针

Reason(原因)

Arrays are best represented by a container type (e.g., vector (owning)) or a span (non-owning). Such containers and views hold sufficient information to do range checking.

数组最好用容器类型(例如,vector(具有所有权))或者span(不包含所有权)表示。容器或span包含可以用于范围检查的信息。

Example, bad(反面示例)

代码语言:javascript
复制
void f(int* p, int n)   // n is the number of elements in p[]
{
    // ...
    p[2] = 7;   // bad: subscript raw pointer
    // ...
}

The compiler does not read comments, and without reading other code you do not know whether p really points to n elements. Use a span instead.

编译器不会读注释行,如果不看其他代码你无法知道p实际上指向n个元素。使用span吧。

Example(示例)

代码语言:javascript
复制
void g(int* p, int fmt)   // print *p using format #fmt
{
    // ... uses *p and p[0] only ...
}
Exception(例外)

C-style strings are passed as single pointers to a zero-terminated sequence of characters. Use zstring rather than char* to indicate that you rely on that convention.

C风格字符串作为指向以0结尾的字符序列的指针传递。使用zstring而不是char*以表明你遵守这个习惯。

Note(注意)

Many current uses of pointers to a single element could be references. However, where nullptr is a possible value, a reference may not be a reasonable alternative.

很多目前指向单独要素的指针可以使用引用。然而,当nullptr也是有效值时引用就不是一个合理的选择。

Enforcement(实施建议)
  • Flag pointer arithmetic (including ++) on a pointer that is not part of a container, view, or iterator. This rule would generate a huge number of false positives if applied to an older code base.
  • 如果一个指针不是来自容器,view或者迭代器并存在指针运算(包括++),进行提示。这条准则如果运用于旧代码会产生大量的假阳性结果(结果有问题但实际上没有问题,译者注)。
  • Flag array names passed as simple pointers
  • 提示用原始指针传递数组的情况。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r2-in-interfaces-use-raw-pointers-to-denote-individual-objects-only


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

关注【面向对象思考】轻松学习每一天!

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Exception(例外)
      • Note(注意)
        • Enforcement(实施建议)
        相关产品与服务
        容器服务
        腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档