有几种方法可以将文本信息传递给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
我的问题是,在任何情况下C ++ 17void read(const std::string&)
都应优先考虑void read(std::string_view)
。假设不需要向后兼容。
您需要零终止吗?如果是这样,则必须使用以下之一:
// by convention: null-terminated
void read(const char*);
// type invariant: null-terminated
void read(std::string const&);
因为std::string_view
是的任何连续范围char const
,所以不能保证它以null结尾,并且试图窥视最后一个字符是未定义的行为。
如果你没有需要空终止,但需要采取数据的所有权,这样做:
void read(std::string );
如果您既不需要空终止也不需要数据所有权或数据修改,那么最好的选择是:
void read(std::string_view );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句