首页 > 解决方案 > 在 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)假设不需要向后兼容。

标签: c++c++17string-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 );

推荐阅读