Skip to content

std::string_view(C++17)

一句话

一种只读的字符串"视图",不拷贝不分配内存,仅持有指针和长度,适合替代 const std::string& 做函数参数。

头文件

#include <string_view>

核心 API 速查

操作签名说明
构造constexpr basic_string_view(const CharT* s, size_type count)从指针和长度构造
构造constexpr basic_string_view(const CharT* s)从 C 字符串构造
长度constexpr size_type size() const返回字符数量
空检查constexpr bool empty() const检查是否为空
元素访问constexpr const CharT& operator[](size_type pos) const访问指定位置字符
数据指针constexpr const CharT* data() const返回底层字符数组指针
截取前缀constexpr void remove_prefix(size_type n)起始位置前移 n
截取后缀constexpr void remove_suffix(size_type n)末尾位置前移 n
子串constexpr basic_string_view substr(size_type pos = 0, size_type count = npos) const返回子串视图
查找constexpr size_type find(basic_string_view v, size_type pos = 0) const查找子串位置

最小示例

cpp
#include <iostream>
#include <string_view>
// Standard: C++17

void print(std::string_view sv) {
    std::cout << sv << "\n";
}

int main() {
    std::string s = "hello";
    print(s);                    // 接受 std::string
    print("world");              // 接受字符串字面量
    std::string_view sv = s;
    sv.remove_prefix(1);         // 变为 "ello"
    print(sv.substr(0, 2));      // 输出 "el"
}

嵌入式适用性:高

  • 零堆分配,仅有指针和长度两个成员,内存开销极小(通常 16 字节)
  • TriviallyCopyable 类型,可安全用于中断上下文或 DMA 传输缓冲区解析
  • 替代 const std::string& 避免隐式 std::string 构造带来的堆分配
  • 需注意生命周期:绝不将临时 std::string 绑定到 string_view

编译器支持

GCCClangMSVC
7.14.019.10

另见


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

基于 VitePress 构建