在 C++17 中引用 const 字符串的语义应该是什么?

Dmi*_*nov 2 c++ string-view c++17

有几种方法可以将文本信息传递给 C++ 中的函数:可以是 c-string/std::string、按值/按引用、左值/右值、常量/可变的。C++17 在标准库中添加了一个新类:std::string_view. string_view 的语义是提供没有所有权的只读文本信息。因此,如果您只需要读取一个字符串,您可以使用:

void read(const char*);        // if you need that in a c-style function or you don't care of the size
void read(const std::string&); // if you read the string without modification in C++98 - C++14
void read(std::string_view);   // if you read the string without modification in C++17
Run Code Online (Sandbox Code Playgroud)

我的问题是在 C++17 中void read(const std::string&)是否应该优先考虑任何情况void read(std::string_view)。假设不需要向后兼容性。

Bar*_*rry 5

需要空终止吗?如果是这样,您必须使用以下之一:

// by convention: null-terminated
void read(const char*);

// type invariant: null-terminated
void read(std::string const&);
Run Code Online (Sandbox Code Playgroud)

因为std::string_view只是 的任何连续范围char const,所以不能保证它是空终止的,并且试图偷看最后一个字符是未定义的行为。

如果你没有需要空终止,但需要采取数据的所有权,这样做:

void read(std::string );
Run Code Online (Sandbox Code Playgroud)

如果您既不需要空终止,也不需要所有权或修改数据,那么您最好的选择是:

void read(std::string_view );
Run Code Online (Sandbox Code Playgroud)