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

网友投稿 638 2022-11-12

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

C++核心准则​SL.str.3:使用zstring或czstring引用C风格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(原因)

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 nullptrvoid f1(czstring s); // s is a C-style string constant or the nullptrvoid 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()的情况。

原文链接

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

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

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

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:GTK KDE应用程序的汉化 转
下一篇:Spring三级缓存解决循环依赖
相关文章

 发表评论

暂时没有评论,来抢沙发吧~