前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.22 使用T*或onwer<T*>指明唯一对象

C++核心准则编译边学-F.22 使用T*或onwer<T*>指明唯一对象

作者头像
面向对象思考
发布2020-03-25 15:24:13
4260
发布2020-03-25 15:24:13
举报

F.22: Use T* or owner<T*> to designate a single object(使用T*或owner<T*>指明唯一对象)

Reason(原因)

Readability: it makes the meaning of a plain pointer clear. Enables significant tool support.

可读性:这可以让裸指针的含义更明确。使重要的工具支持有效。

译者注

译者注:owner<T*>是gsl(准则支持库)提供的一个功能,从编译的角度来看和T*的含义一致,但是附加了所有权语义,可以帮助程序员理解代码和工具检查。

Note(注意)

In traditional C and C++ code, plain T* is used for many weakly-related purposes, such as:

在传统的C和C++代码中,裸指针用于很多没有什么关系的目的,例如:

  • Identify a (single) object (not to be deleted by this function) 表示一个(单一)对象(不会被本函数删除)
  • Point to an object allocated on the free store (and delete it later) 指向一个从自由存储上获取的对象(以后会删除)
  • Hold the nullptr 持有nullptr
  • Identify a C-style string (zero-terminated array of characters) 表示一个C风格字符串(以0结尾的字符数组)
  • Identify an array with a length specified separately 表示一个数组,长度被另外定义
  • Identify a location in an array 表示数组的首地址

This makes it hard to understand what the code does and is supposed to do. It complicates checking and tool support.

这样做的结果是很难理解代码在做什么和被预期做什么。无论是检查还是工具支持都会复杂。

Example(示例)
代码语言:javascript
复制
void use(int* p, int n, char* s, int* q)
{
    p[n - 1] = 666; // Bad: we don't know if p points to n elements;
                    // assume it does not or use span<int>
    cout << s;      // Bad: we don't know if that s points to a zero-terminated array of char;
                    // assume it does not or use zstring
    delete q;       // Bad: we don't know if *q is allocated on the free store;
                    // assume it does not or use owner
}

译者注:这可能是我们每天都能见到的指针用法,很难看出它们到底是前面提供的那种用法。

better(稍好)

代码语言:javascript
复制
void use2(span<int> p, zstring s, owner<int*> q)
{
    p[p.size() - 1] = 666; // OK, a range error can be caught
    cout << s; // OK
    delete q;  // OK
}

Note(注意)

owner<T*> represents ownership, zstring represents a C-style string.

owner<T*>表现所有权,zstring表达C风格的字符串

Also: Assume that a T* obtained from a smart pointer to T (e.g., unique_ptr<T>) points to a single element.

参考:假定T*是从指向T的智能指针(例如unique_prt<T>)获取,指向单一对象的指针。

See also: Support library

参考:支持库。

See also: Do not pass an array as a single pointer

参考:不要使用单一指针传递数组

Enforcement(实施建议)
  • (Simple) ((Bounds)) Warn for any arithmetic operation on an expression of pointer type that results in a value of pointer type. (简单)((边界))警告所有针对指针表达式,并得到指针类型结果的算数操作。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-17,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.22: Use T* or owner<T*> to designate a single object(使用T*或owner<T*>指明唯一对象)
    • Reason(原因)
      • Note(注意)
        • Example(示例)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档