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)
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(实施建议)
原文链接
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