Skip to content

std::string_view (C++17)

In a Nutshell

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

cpp
#include <string_view>

Core API Cheat Sheet

OperationSignatureDescription
Constructionstring_view(const CharT*, size_t)Constructs from a pointer and length
Constructionstring_view(const CharT*)Constructs from a C-style string
Lengthsize()Returns the number of characters
Empty Checkempty()Checks if the view is empty
Element Accessoperator[]Accesses character at the specified position
Data Pointerdata()Returns the underlying character array pointer
Remove Prefixremove_prefix(size_t n)Moves the start position forward by n
Remove Suffixremove_suffix(size_t n)Moves the end position backward by n
Substringsubstr(pos, len)Returns a substring view
Findfind(str)Finds the position of a substring

Minimal Example

cpp
#include <string_view>
#include <iostream>

void print_sv(std::string_view sv) {
    std::cout << sv << std::endl;
}

int main() {
    // No copy, just a view
    std::string str = "Hello";
    std::string_view sv = str;

    print_sv("World"); // Implicit conversion from const char*
    print_sv(sv);      // Pass by view
}

Embedded Applicability: High

  • Zero heap allocation. It has only two members (pointer and length), resulting in minimal memory overhead (typically 16 bytes).
  • A TriviallyCopyable type, making it safe for use in interrupt contexts or for parsing DMA transfer buffers.
  • Replaces const std::string& to avoid implicit std::string construction and the associated heap allocation.
  • Caution: Be mindful of lifetimes. Never bind a temporary std::string to a std::string_view.

Compiler Support

GCCClangMSVC
7.14.019.10

See Also


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

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05