前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​SL.str.3:使用zstring或czstring引用C风格0结尾的字符串序列

C++核心准则​SL.str.3:使用zstring或czstring引用C风格0结尾的字符串序列

作者头像
面向对象思考
发布2020-10-30 11:32:10
6820
发布2020-10-30 11:32:10
举报

SL.str.3: Use zstring or czstring to refer to a C-style, zero-terminated, sequence of characters

SL.str.3:使用zstring或czstring引用C风格0结尾的字符串序列

Reason(原因)

Readability. Statement of intent. A plain char* can be a pointer to a single character, a pointer to an array of characters, a pointer to a C-style (zero-terminated) string, or even to a small integer. Distinguishing these alternatives prevents misunderstandings and bugs.

可读性。表达意图。直接的char*可以是指向单个的字符的指针,指向字符数组的指针,指向C风格(0结尾)字符串的指针,甚至指向小整数的指针。区别这些情况可以防止误解和错误。

Example(示例)

代码语言:javascript
复制
void f1(const char* s); // s is probably a string

All we know is that it is supposed to be the nullptr or point to at least one character

我们得到的所有信息就是它可能是空指针或者指向至少一个字符。

代码语言:javascript
复制
void f1(zstring s);     // s is a C-style string or the nullptr
void f1(czstring s);    // s is a C-style string constant or the nullptr
void f1(std::byte* s);  // s is a pointer to a byte (C++17)
Note(注意)

Don't convert a C-style string to string unless there is a reason to.

除非存在合理的理由,不要将C风格字符串转变为string。

Note(注意)

Like any other "plain pointer", a zstring should not represent ownership.

像其他“直接指针”一样,zstring不应用于表现所有权。

Note(注意)

There are billions of lines of C++ "out there", most use char* and const char* without documenting intent. They are used in a wide variety of ways, including to represent ownership and as generic pointers to memory (instead of void*). It is hard to separate these uses, so this guideline is hard to follow. This is one of the major sources of bugs in C and C++ programs, so it is worthwhile to follow this guideline wherever feasible.

存在数十亿规模的代码,大部分使用char*和const char*的代码都没有说明意图。它们被使用的方式多种多样,包括表现所有权和作为指向内存的通用指针(代替void*)。很难区分这些用法,因此本准则难以遵守。这是C和C++代码中错误的一个主要来源,因此重要的是只要可能就遵守本准则。

Enforcement(实施建议)

  • Flag uses of [] on a char* 标记对char*使用下标运算的情况
  • Flag uses of delete on a char* 标记对char*使用delete操作的情况
  • Flag uses of free() on a char* 标记使用char*类型实参调用free()的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slstr3-use-zstring-or-czstring-to-refer-to-a-c-style-zero-terminated-sequence-of-characters

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.str.3: Use zstring or czstring to refer to a C-style, zero-terminated, sequence of characters
  • SL.str.3:使用zstring或czstring引用C风格0结尾的字符串序列
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档