Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 171 ยท Strings

std::string_view

Learn C++ std::string_view - cheap non-owning views of text, the best string parameter type, substr without copying, remove_prefix, and the dangling-view traps.

A std::string owns its characters: it allocates memory, copies text into it and frees it when it dies. That is exactly what you want for storing text, but it is wasteful when a function only needs to look at some characters. Passing a string literal to a const std::string& parameter quietly builds a temporary std::string, and taking a substr copies the piece into new memory.

std::string_view (C++17, header <string_view>) fixes this. It is a tiny object that holds just two things: a pointer to the first character and a length. It doesn't own anything, never allocates and is cheap to copy. You can point it at a string literal, a std::string, a character array or any part of one. In this lesson you'll learn how to create views, why they are the best type for read-only string parameters, how to slice text without copying, and the one big rule that keeps views safe: the text must outlive the view.

What a string_view is

Think of a std::string_view as a window onto characters that live somewhere else. The window has a start and a width. Moving or resizing the window is free; the characters behind it are never copied.

C++ Creating string views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

On a 64-bit system a view is 16 bytes: an 8-byte pointer and an 8-byte length, no matter how long the text is. Copying one costs about as much as copying two integers, which is why you pass views by value, never by reference.

The sv suffix comes from the namespace std::literals::string_view_literals. Pulling just that small namespace into a function with using namespace is fine and common; it only adds literal suffixes. The suffix matters in one case: "a\0b"sv has size 3, while std::string_view{"a\0b"} stops at the embedded null and has size 1.

A view supports most of the read-only interface of std::string:

Works on a view Notes
size(), length(), empty() constant time, the length is stored
[], at(), front(), back(), data() read-only access; at() throws std::out_of_range
find, rfind, find_first_of, โ€ฆ same rules and npos as on std::string
starts_with, ends_with (C++20), contains (C++23) prefix, suffix and substring tests
substr, remove_prefix, remove_suffix return or change the view, never the text
==, <, <=>, compare compare the characters, like strings
range-based for, iterators iterate over characters

What you can't do is change the characters. There is no append, insert, erase or replace, and operator[] returns a const char&. A view is read-only by design.

The best parameter type for read-only text

Before C++17, the standard advice was "pass strings as const std::string&". That avoids copying when the caller already has a std::string, but it has a hidden cost: when the caller passes a string literal or a const char*, C++ must build a temporary std::string first, which can allocate memory. A std::string_view parameter accepts all of these without any conversion work.

The program below replaces the global operator new with a version that counts allocations, so you can see the difference. (Replacing the global allocator is a legitimate C++ feature, and it's a handy trick for measuring code like this.)

C++ Counting allocations: const std::string& vs string_view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The const std::string& version allocates once per call because the 43-character sentence is too long for the small-string buffer inside std::string. The view version allocates nothing, whether you hand it a pointer, a literal or an existing std::string.

Rules of thumb for parameters:

  • Read-only text โ†’ std::string_view, passed by value.
  • The function stores the text (for example in a member variable) โ†’ take a std::string by value and std::move it into place, or take a view and convert it explicitly. See Parameters for the details.
  • The function must hand the text to a C API that needs a null terminator โ†’ take const std::string& or const char*. A view may not end with '\0' (more on that below).

Slicing without copying

std::string::substr returns a new std::string, so it copies. std::string_view::substr returns another view into the same characters, so it costs nothing. Two more members shrink a view in place: remove_prefix(n) moves the start forward by n, and remove_suffix(n) moves the end back by n.

That makes views ideal for parsing. You can trim, split and inspect text while the original characters stay exactly where they are.

C++ Trimming and splitting with views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

None of these functions allocate any text. The std::vector allocates room for its views, but every view still points into line. The npos trick in split works because substr(0, npos) means "everything up to the end".

substr, remove_prefix and remove_suffix have different safety rules. substr(pos) throws std::out_of_range if pos > size(). remove_prefix(n) and remove_suffix(n) with n > size() are undefined behavior: they don't check. Validate the count first, as split does by only removing what find reported.

Converting between string and string_view

The conversions go in one direction easily and the other direction deliberately:

  • std::string โ†’ std::string_view is implicit. Any std::string can be passed where a view is expected.
  • std::string_view โ†’ std::string is explicit, because it allocates and copies. Write std::string{view} or std::string(view).

Many std::string members accept views directly, so mixing them is smooth: s += view, s.append(view), s.insert(0, view), s.find(view) and comparisons like s == view all work. One gap in C++23: std::string + std::string_view with + doesn't compile until C++26 adds that overload. Use += or std::format instead.

C++
std::string_view greeting = "Hello";
std::string message{greeting};   // explicit copy into an owning string
message += ", ";
message += std::string_view{"world"};
// std::string bad = greeting;   // error: no implicit conversion

Views are not null-terminated

A std::string always keeps a '\0' after its last character, so c_str() is safe for C functions. A view makes no such promise. If it was cut out of the middle of some text, data() points at characters that keep going past the end of the view. Passing view.data() to a function that expects a C string (std::printf("%s"), std::strlen, fopen, most operating-system APIs) reads too far.

C++ data() keeps going past the view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Here the bad line prints the whole literal only because the literal happens to have a null terminator a few characters later. With a view into a buffer that has no '\0' at all, it would read random memory. When a C API needs a terminator, make a std::string from the view and call c_str(). You'll see more about C strings in C-Style Strings and Character Arrays.

Dangling views: the one rule

Because a view only points at characters, it is only valid while those characters exist and haven't moved. A view that outlives its text is dangling, and reading it is undefined behavior: the program might print garbage, print the right thing by luck, or crash. The compiler usually can't warn you. Here are the three classic ways to get one:

C++
// 1. Returning a view of a local string
std::string_view make_label(int id) {
    std::string label = "item-" + std::to_string(id);
    return label;               // BUG: label is destroyed when the function returns
}

// 2. Viewing a temporary
std::string first = "Ada", last = "Lovelace";
std::string_view full = first + " " + last;   // BUG: the temporary string dies at the ;
std::println("{}", full);                      // reads freed memory

// 3. Changing the string the view points into
std::string text = "short";
std::string_view view = text;
text += " but now much longer than the small buffer";  // may reallocate
std::println("{}", view);                              // BUG: view points at the old buffer

The fixes follow from the rule:

  • Return std::string from functions that create text. Returning a view is fine only when it points into something the caller already owns, like trim above, which returns part of its argument.
  • Store std::string in classes and containers that keep text around. A member of type std::string_view is a red flag unless you can prove the text outlives the object (string literals always do; they live for the whole program).
  • Don't keep a view across changes to the string it views. Make the view again after modifying the string.
C++ Safe patterns: views into text that outlives them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Watch auto with views. auto part = file_extension(make_label(7) + ".txt"); compiles, but part views a temporary string that is destroyed at the end of the line. Holding the result of a view-returning function in a variable is safe only when the argument outlives that variable.

During development, AddressSanitizer (-fsanitize=address) catches most dangling-view reads at runtime as "heap-use-after-free" or "stack-use-after-return" errors. See Undefined Behavior and Memory Safety.

Views as map keys and lookups

A common need is looking up a view in a std::map<std::string, ...>. By default, map.find(view) won't compile, because find expects a std::string. If you declare the map with the transparent comparator std::less<>, find accepts anything comparable with the key, including views, and no temporary string is built:

C++
std::map<std::string, int, std::less<>> stock{{"apples", 12}, {"pears", 4}};
std::string_view wanted = "pears";
if (auto it = stock.find(wanted); it != stock.end()) {
    std::println("{} in stock", it->second);   // no std::string was created
}

You'll meet maps properly in std::map and std::multimap. For the hash-based std::unordered_map, the same trick needs a transparent hash as well; that lesson covers it.

When to use string_view

Situation Use
Function parameter, read-only text std::string_view by value
Return a piece of an argument std::string_view (document that it points into the argument)
Return newly built text std::string
Class member or container element that stores text std::string
Table of fixed names ("Mon", "Tue", โ€ฆ) constexpr std::string_view or std::array of them
Text that must be null-terminated for a C API std::string (call c_str())

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a std::string_view contain?

    A view is just a pointer plus a size. It owns nothing, never allocates and doesn't require a null terminator.
  2. 2. std::string_view v = std::string("abc") + "def"; What is wrong with this line?

    The view points into a temporary that dies at the semicolon. Any later use of v reads freed memory, which is undefined behavior.
  3. 3. std::string_view s = "one two three"; s.remove_prefix(4); What does s view now?

    remove_prefix moves the start of the view forward by 4 characters. The underlying characters are not changed at all.
  4. 4. Why should you not pass view.data() to std::printf("%s", ...)?

    A view of part of a string ends wherever its length says, but %s keeps reading until it finds a '\0'. Use %.*s with the size, or make a std::string and call c_str().
  5. 5. Which is the best return type for a function that builds a new label like "item-7"?

    New text needs an owner. Returning a view or a reference to a local string would dangle; return std::string by value (copy elision makes this cheap).

Summary

  • std::string_view is a non-owning, read-only window onto characters: a pointer plus a length, 16 bytes on 64-bit systems, passed by value.
  • It is the best parameter type for read-only text: literals, const char* and std::string all pass without allocating.
  • substr, remove_prefix and remove_suffix slice the view without copying; remove_prefix/remove_suffix don't check bounds.
  • std::string โ†’ view is implicit; view โ†’ std::string must be explicit (std::string{view}).
  • Views are not null-terminated. Don't pass data() to C functions that expect a C string.
  • The text must outlive the view. Never return a view of a local, never view a temporary you keep, and don't keep a view across changes to its string.
  • Store text in std::string; use std::less<> maps for lookups with views.

Next: Formatting with std::format and std::print, where you'll control width, alignment, precision and number bases.