有几种方法可以将文本信息传递到C++中的函数:它可以是c-string/std::string,by value/by reference,lvalue/rvalue,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我的问题是,在void read(const std::string&)中是否应该选择void read(std::string_view)而不是C++17,假设不需要向后兼容性。
发布于 2020-07-07 18:55:11
你需要零终止吗?如果是这样的话,您必须使用其中之一:
// by convention: null-terminated
void read(const char*);
// type invariant: null-terminated
void read(std::string const&);因为std::string_view只是char const的任何连续范围,所以不能保证它是以空结尾的,而且它是未定义的行为,试图查看最后一个字符。
如果不需要空终止,但需要获得数据的所有权,请执行以下操作:
void read(std::string );如果您既不需要空终止,也不需要拥有或修改数据,那么是的,您最好的选择是:
void read(std::string_view );https://stackoverflow.com/questions/62781737
复制相似问题