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

What should be the semantics of a reference to const string in C++17?

本文关键字:语义 是什么 字符串 const C++17 引用      更新时间:2023-10-16

有几种方法可以将文本信息传递到C++中的函数中:可以是C-string/std::string、by-value/by-reference、lvalue/rvale、const/mutable。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

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

是否需要null终止?如果是这样,你必须使用其中一个:

// by convention: null-terminated
void read(const char*);
// type invariant: null-terminated
void read(std::string const&);

因为std::string_view只是char const的任何连续范围,所以不能保证它是以null结尾的,并且试图越过最后一个字符是未定义的行为。

如果您执行不需要null终止,但需要获得数据所有权,请执行以下操作:

void read(std::string );

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

void read(std::string_view );