std::string_view
什么是 std::string_view
std::string_view 是 C++17 在 <string_view> 头文件中引入的一个轻量级、非拥有(non-owning)的字符串引用类型。它内部只存储两个东西:一个指向字符序列的指针和一个长度值。它不拥有底层的字符数据,不分配内存,也不管理字符串的生命周期。
在 C++17 之前,函数参数如果要接受各种形式的字符串(std::string、const char*、字符数组等),通常用 const std::string&。问题是:如果调用者传的是 const char*,编译器会隐式构造一个临时的 std::string,涉及内存分配和数据拷贝。std::string_view 解决了这个问题:无论传入的是 std::string、const char* 还是字符数组,都可以零拷贝地创建一个 string_view。
string_view 的另一个重要优势是 substr 操作的复杂度是 O(1)——它只是调整指针和长度,不拷贝任何数据。std::string 的 substr 则是 O(n) 的,因为它要创建一个新字符串。
头文件与基本声明
#include <string_view>
std::string_view sv1 = "hello world"; // 从字符串字面量
std::string str = "hello";
std::string_view sv2 = str; // 从 std::string
std::string_view sv3{"hello", 5}; // 从指针 + 长度
std::string_view sv4; // 空视图核心接口说明
string_view 提供了和 std::string 几乎完全一致的只读接口:
| 成员函数 | 说明 |
|---|---|
data() | 返回底层字符数组的指针 |
size() / length() | 返回字符数 |
empty() | 是否为空 |
operator[] / at() | 按索引访问字符 |
front() / back() | 首/尾字符 |
substr(pos, count) | 返回子视图(O(1),不拷贝) |
find() / rfind() | 查找子串 |
find_first_of() / find_last_of() | 查找字符集合 |
compare() | 字符串比较 |
starts_with() / ends_with() | C++20 新增,检查前缀/后缀 |
contains() | C++23 新增,检查是否包含子串 |
remove_prefix(n) | 从前面移除 n 个字符(修改视图,不修改数据) |
remove_suffix(n) | 从后面移除 n 个字符 |
copy(dest, count, pos) | 拷贝字符到目标缓冲区 |
不支持的操作:所有修改字符串内容的操作(append、insert、erase、replace、push_back 等),因为 string_view 是只读的。
基本示例
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
// ============================
// 示例1:作为函数参数(零拷贝)
// ============================
// 接受任何形式的字符串,不触发拷贝
void print_info(std::string_view sv) {
std::cout << "内容: " << sv << std::endl;
std::cout << "长度: " << sv.size() << std::endl;
std::cout << "首字符: " << sv.front() << std::endl;
}
// ============================
// 示例2:O(1) 的 substr
// ============================
void substr_demo() {
std::string_view sv = "Hello, World!";
// substr 返回一个新的 string_view,只是调整指针和长度
// 不分配内存,不拷贝字符
std::string_view hello = sv.substr(0, 5); // "Hello"
std::string_view world = sv.substr(7, 5); // "World"
std::cout << hello << " | " << world << std::endl;
// 对比:std::string 的 substr 会创建新字符串(O(n))
// std::string s = "Hello, World!";
// std::string hello_str = s.substr(0, 5); // 分配内存 + 拷贝
}
// ============================
// 示例3:remove_prefix / remove_suffix
// ============================
void trim_demo() {
std::string_view sv = " hello world ";
// 去掉前导空格
while (!sv.empty() && sv.front() == ' ') {
sv.remove_prefix(1);
}
// 去掉尾部空格
while (!sv.empty() && sv.back() == ' ') {
sv.remove_suffix(1);
}
std::cout << "trim 结果: [" << sv << "]" << std::endl; // [hello world]
}
// ============================
// 示例4:字符串查找
// ============================
void find_demo() {
std::string_view sv = "one,two,three,four,five";
// 查找逗号
auto pos = sv.find(',');
if (pos != std::string_view::npos) {
std::cout << "第一个逗号位置: " << pos << std::endl; // 3
std::cout << "逗号之前: " << sv.substr(0, pos) << std::endl; // one
}
// 简单的按逗号分割
std::cout << "分割结果: ";
std::string_view remaining = sv;
while (!remaining.empty()) {
auto comma = remaining.find(',');
if (comma == std::string_view::npos) {
std::cout << "[" << remaining << "] ";
break;
}
std::cout << "[" << remaining.substr(0, comma) << "] ";
remaining.remove_prefix(comma + 1);
}
std::cout << std::endl;
}
// ============================
// 示例5:与不同字符串类型的互操作
// ============================
void interop_demo() {
// 从字符串字面量
std::string_view sv1 = "literal";
// 从 std::string
std::string str = "std::string";
std::string_view sv2 = str;
// 从 char 数组
char arr[] = "char array";
std::string_view sv3 = arr;
// 从指针 + 长度(处理非 null-terminated 的情况)
const char* data = "partial string view";
std::string_view sv4(data, 7); // 只取前 7 个字符
std::cout << sv1 << std::endl;
std::cout << sv2 << std::endl;
std::cout << sv3 << std::endl;
std::cout << sv4 << std::endl; // "partial"
// 从 string_view 创建 std::string(需要显式转换)
std::string new_str(sv1); // 显式构造
std::string new_str2{sv2}; // 花括号初始化
// std::string bad = sv1; // C++17 中隐式转换是允许的
}
int main() {
std::cout << "=== 函数参数 ===" << std::endl;
print_info("C string literal"); // const char* -> string_view
print_info(std::string("std::string")); // string -> string_view
print_info(std::string_view("view")); // string_view -> string_view
std::cout << "\n=== substr ===" << std::endl;
substr_demo();
std::cout << "\n=== trim ===" << std::endl;
trim_demo();
std::cout << "\n=== find ===" << std::endl;
find_demo();
std::cout << "\n=== 互操作 ===" << std::endl;
interop_demo();
return 0;
}与 std::string 和 const char* 的对比
| 特性 | std::string_view | const std::string& | const char* |
|---|---|---|---|
| 拥有数据 | 否 | 否(引用别人的) | 否 |
| 内存分配 | 无 | string 本身可能分配 | 无 |
| 从 const char* 构造 | 零拷贝 | 触发 string 构造(拷贝) | 直接使用 |
| 从 std::string 构造 | 零拷贝 | 直接引用 | 调用 c_str() |
| substr 复杂度 | O(1) | O(n) | 手动指针操作 |
| null 终止保证 | 不保证 | 保证 | 保证 |
| 知道长度 | 是(存储了 size) | 是 | 否(需要 strlen) |
| sizeof | 通常 16 字节 | 通常 32 字节 | 8 字节(指针) |
进阶用法
#include <iostream>
#include <string>
#include <string_view>
#include <algorithm>
#include <vector>
// ============================
// 进阶1:高效的字符串解析
// ============================
// 解析 "key=value" 格式,零拷贝
std::pair<std::string_view, std::string_view>
parse_key_value(std::string_view input) {
auto eq_pos = input.find('=');
if (eq_pos == std::string_view::npos) {
return {input, {}};
}
return {input.substr(0, eq_pos), input.substr(eq_pos + 1)};
}
// 按分隔符分割字符串,零拷贝
std::vector<std::string_view> split(std::string_view str, char delimiter) {
std::vector<std::string_view> result;
while (!str.empty()) {
auto pos = str.find(delimiter);
if (pos == std::string_view::npos) {
result.push_back(str);
break;
}
result.push_back(str.substr(0, pos));
str.remove_prefix(pos + 1);
}
return result;
}
// ============================
// 进阶2:constexpr 字符串操作
// ============================
// string_view 的很多操作都是 constexpr 的
constexpr std::string_view trim_front(std::string_view sv) {
while (!sv.empty() && sv.front() == ' ') {
sv.remove_prefix(1);
}
return sv;
}
// 编译期字符串检查
constexpr bool starts_with_hello(std::string_view sv) {
return sv.size() >= 5 && sv.substr(0, 5) == "hello";
}
static_assert(starts_with_hello("hello world"));
static_assert(!starts_with_hello("world hello"));
int main() {
// 解析 key=value
std::string config = "host=localhost;port=8080;debug=true";
auto items = split(config, ';');
for (auto item : items) {
auto [key, value] = parse_key_value(item);
std::cout << " key=[" << key << "] value=[" << value << "]" << std::endl;
}
// constexpr 操作
constexpr auto trimmed = trim_front(" hello");
std::cout << "trim: [" << trimmed << "]" << std::endl;
return 0;
}适用场景
- 函数参数接受字符串时,用
std::string_view代替const std::string& - 字符串解析(分割、查找、提取子串)——substr 是 O(1)
- 处理大量文本数据时避免不必要的字符串拷贝
- 编译期字符串处理(constexpr 上下文)
- 需要同时接受
const char*和std::string的接口
常见问题
string_view 可以保证 null 终止吗?
不保证。string_view 只记录指针和长度,不关心最后一个字符后面是不是 \0。如果你需要把 string_view 传给要求 null-terminated 字符串的 C API(比如 fopen、printf),必须先转换为 std::string(std::string(sv))或确认底层数据确实是 null 终止的。
string_view 的生命周期问题怎么处理?
这是 string_view 最大的陷阱。string_view 不拥有数据,如果底层数据被销毁了,string_view 就变成了悬空引用。典型的错误是返回一个指向局部变量的 string_view,或者存储一个指向临时 string 的 string_view。规则很简单:string_view 的生命周期不能超过它引用的字符串的生命周期。
// 危险!返回指向临时对象的 string_view
std::string_view bad() {
std::string temp = "hello";
return temp; // temp 被销毁,返回的 view 悬空
}
// 安全:返回指向字面量的 view(字面量有静态存储期)
std::string_view ok() {
return "hello"; // 字符串字面量一直存在
}string_view 作为函数返回值安全吗?
取决于返回的 view 指向的数据的生命周期。如果指向字符串字面量、全局/静态变量、或者调用者拥有的字符串,就是安全的。如果指向函数内的局部变量,就是悬空引用。一般建议:只在你能确保底层数据存活的情况下返回 string_view。
string_view 和 const string& 性能差多少?
当传入 const char* 时差异最大:const string& 需要构造临时 string(可能堆分配),string_view 零拷贝。传入 std::string 时两者差异很小。substr 操作上差异巨大:string_view 的 substr 是 O(1),string 的 substr 是 O(n)。
注意事项
- string_view 不保证 null 终止,传给 C API 前要转换为
std::string或c_str() - string_view 不拥有数据,必须确保底层数据在 view 的使用期间一直存活
- 不要存储指向临时
std::string的 string_view(悬空引用) remove_prefix和remove_suffix修改的是视图本身,不是底层数据- string_view 可以从
std::string隐式构造,但从 string_view 到std::string需要显式构造 - 作为类成员存储 string_view 时要格外小心生命周期问题——通常存
std::string更安全 std::string_view::npos和std::string::npos是相同的值(size_type的最大值)
编译器支持情况
| 编译器 | 最低支持版本 |
|---|---|
| GCC | 7.0 |
| Clang | 4.0 |
| MSVC | 19.10 (VS 2017) |
总结
std::string_view 是 C++17 中对字符串处理性能影响最大的特性之一。它提供了零拷贝的只读字符串引用,内部只有一个指针和一个长度。作为函数参数类型,它统一接受 const char*、std::string、字符数组等各种字符串形式而不触发拷贝。substr 操作从 O(n) 降到 O(1) 对文本解析场景是巨大的性能提升。使用 string_view 最需要注意的是生命周期问题:它不拥有底层数据,你必须确保数据在 view 使用期间一直存活。最佳实践是:函数参数用 string_view 代替 const string&,类成员和长期存储仍然用 std::string。