C++17 引入 std::string_view(位于 <string_view> 头文件),提供对现有字符串的只读访问,不制作副本。
std::string 初始化和复制开销大。string_view 解决了这一问题,允许零拷贝字符串操作。
#include <iostream>
#include <string>
#include <string_view>
int main() {
using namespace std::string_literals;
using namespace std::string_view_literals;
std::cout << "foo\n"; // C 样式字符串
std::cout << "goo\n"s; // std::string 字面值
std::cout << "moo\n"sv; // std::string_view 字面值
return 0;
}
与 std::string 不同,string_view 完全支持 constexpr:
#include <iostream>
#include <string_view>
int main() {
constexpr std::string_view s{ "Hello, world!" };
std::cout << s << '\n'; // 编译时替换
return 0;
}
视图查看的结果取决于正在查看的对象。如果原始对象被修改或销毁,将导致未定义行为。
修改 std::string 会使所有 string_view 失效。
局部变量在函数末尾被销毁,返回指向局部变量的 string_view 会悬挂:
// 安全:C 字符串字面值不会失效
std::string_view getBoolName(bool b) {
if (b) return "true";
return "false";
}
// 安全:返回函数参数
std::string_view firstAlphabetical(
std::string_view s1, std::string_view s2) {
return s1 < s2 ? s1 : s2;
}
作为只读函数参数——允许零拷贝传入 C 字符串、std::string 或 string_view。