Skip to content

std::string_view (C++17) ​

In a nutshell ​

A read-only "view" of a string that copies nothing and allocates no memory — it holds just a pointer and a length, making it a good replacement for const std::string& as a function parameter.

Header file ​

#include <string_view>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructionconstexpr basic_string_view(const CharT* s, size_type count)Constructs from a pointer and a length
Constructionconstexpr basic_string_view(const CharT* s)Constructs from a C string
Lengthconstexpr size_type size() constReturns the number of characters
Empty checkconstexpr bool empty() constChecks whether the view is empty
Element accessconstexpr const CharT& operator[](size_type pos) constAccesses the character at the given position
Data pointerconstexpr const CharT* data() constReturns a pointer to the underlying character array
Remove prefixconstexpr void remove_prefix(size_type n)Advances the start position by n
Remove suffixconstexpr void remove_suffix(size_type n)Pulls the end position back by n
Substringconstexpr basic_string_view substr(size_type pos = 0, size_type count = npos) constReturns a substring view
Findconstexpr size_type find(basic_string_view v, size_type pos = 0) constFinds the position of a substring

Minimal Example ​

C++
#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);                    // accepts a std::string
    print("world");              // accepts a string literal
    std::string_view sv = s;
    sv.remove_prefix(1);         // now "ello"
    print(sv.substr(0, 2));      // outputs "el"
}

Embedded Suitability: High ​

  • Zero heap allocation — just two members, a pointer and a length, so the memory overhead is tiny (typically 16 bytes)
  • A TriviallyCopyable type, safe to use in interrupt contexts or when parsing DMA transfer buffers
  • Replaces const std::string& to avoid the heap allocation caused by an implicit std::string construction
  • Watch the lifetime: never bind a temporary std::string to a string_view

Compiler Support ​

GCCClangMSVC
7.14.019.10

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05