c++ - 在 C++17 中引用 const 字符串的语义应该是什么?
问题描述
有几种方法可以将文本信息传递给 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++17 中void 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
,所以不能保证它是空终止的,并且试图窥视最后一个字符是未定义的行为。
如果您不需要空终止,但需要获取数据的所有权,请执行以下操作:
void read(std::string );
如果您既不需要空终止,也不需要所有权或修改数据,那么是的,您最好的选择是:
void read(std::string_view );
推荐阅读
- image - 将图像/符号定位在某些单词下方
- java - 如何将对象添加到 Created 类类型的数组?
- r - 复杂的 dplyr group_by 过滤
- sass - 使用 scss 覆盖 bootstrap 4 主按钮样式
- javascript - 我如何从另一个类调用 javascript 类并在数组中推送(追加)值?
- python - 如何修复错误“文件名、目录名或卷标语法不正确”?
- ruby - 使用 selenium 更改 Edge 的默认文件下载路径
- awk - 用包含替换位数的模式替换字符串中的数字
- logging - 删除向导请求日志格式
- sparql - RDFLib 在小图上的第一次查询很慢(56 个三元组)