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

面向对象思考

共 2509字,需浏览 6分钟

 · 2020-10-24

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

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

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

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


新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




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

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

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



浏览 25
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报