首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.25 使用zstring或not_null<zstring>表示C风格字符串

C++核心准则编译边学-F.25 使用zstring或not_null<zstring>表示C风格字符串

作者头像
面向对象思考
发布2020-03-25 14:55:33
3430
发布2020-03-25 14:55:33
举报

F.25: Use a zstring or a not_null<zstring> to designate a C-style string

F.25 使用zstring或not_null<zstring>表示C风格字符串

Reason(原因)

C-style strings are ubiquitous. They are defined by convention: zero-terminated arrays of characters. We must distinguish C-style strings from a pointer to a single character or an old-fashioned pointer to an array of characters.

C风格字符串无处不在。按照惯例,它们定义的是以0结尾的字符数组。我们必须区分指向单一字符的指针和过时的指向字符数组的指针。

If you don't need null termination, use string_view.

如果不需要0结尾,则使用string_view。

译者注:string_view是C++17引入的新特性,可以高效安全地管理字符型数组。这个数组不要求以0结尾。

Example(示例)

Consider(考虑以下代码):

int length(const char* p);

When I call length(s) should I check if s is nullptr first? Should the implementation of length() check if p is nullptr?

当我调用length(s)时,应该先检查s是否为nullptr吗?length()的实现应该检查p是否为nullptr吗?

// the implementor of length() must assume that p == nullptr is possibleint length(zstring p);
// it is the caller's job to make sure p != nullptrint length(not_null<zstring> p);

译者注:zstring表明p是以0结尾的字符串数组,而no_null<zstring>则表明p是一个不能为空的以0结尾的字符串数组。这样声明参数之后,是否需要检查,应该由谁检查就明确了。

Note(注意)

zstring does not represent ownership.

zstring没有表达所有权。

See also: Support library

参见:支持库https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-gsl

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.25: Use a zstring or a not_null<zstring> to designate a C-style string
    • Reason(原因)
      • Example(示例)
        • Note(注意)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档