zstring
or a not_null<zstring>
to designate a C-style stringF.25 使用zstring或not_null<zstring>表示C风格字符串
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结尾。
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结尾的字符串数组。这样声明参数之后,是否需要检查,应该由谁检查就明确了。
zstring
does not represent ownership.
zstring没有表达所有权。
See also: Support library
参见:支持库https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-gsl