Skip to content

std::string_view (C++17)

In a Nutshell

A read-only string "view" that performs no copying or memory allocation. It only holds a pointer and a length, making it ideal for replacing const std::string& as a function parameter.

#include <string_view>

Core API Cheat Sheet

OperationSignatureDescription
Constructconstexpr basic_string_view(const CharT* s, size_type count)Construct from a pointer and length
Constructconstexpr basic_string_view(const CharT* s)Construct from a C string
Lengthconstexpr size_type size() constReturn the number of characters
Empty checkconstexpr bool empty() constCheck if it is empty
Element accessconstexpr const CharT& operator[](size_type pos) constAccess the character at the specified position
Data pointerconstexpr const CharT* data() constReturn a pointer to the underlying character array
Remove prefixconstexpr void remove_prefix(size_type n)Advance the starting position by n
Remove suffixconstexpr void remove_suffix(size_type n)Move the ending position back by n
Substringconstexpr basic_string_view substr(size_type pos = 0, size_type count = npos) constReturn a substring view
Findconstexpr size_type find(basic_string_view v, size_type pos = 0) constFind the position of a substring

Minimal Example

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"
}

Embedded Applicability: High

  • Zero heap allocation; it only has two members (a pointer and a length), resulting in minimal memory overhead (typically 16 bytes).
  • A TriviallyCopyable type, safe to use in interrupt contexts or for parsing DMA transfer buffers.
  • Replaces const std::string& to avoid heap allocations caused by implicit std::string construction.
  • Note on lifetime: never bind a temporary std::string to a string_view.

Compiler Support

GCCClangMSVC
7.14.019.10

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress