skip to content

What is C++17's std::string_view, and why do you pass it by value instead of by const reference?

level: juniorimportance: should knowfreq 60%

answer

  1. borrowed, not owned
  2. two machine words
  3. trivially copyable
  4. literal without allocation
  5. explicit back to std::string

basics

~20 s

std::string_view is a read-only, non-owning pointer and length over characters someone else owns. It is two words and trivially copyable, so passing by value is as cheap as a reference without the indirection, and literals convert without allocating.

solid answer

~50 s

`std::string_view` (C++17, header `<string_view>`) is a pointer to characters plus a length. It owns nothing and cannot modify the text. `const char*` and `std::string` convert to it implicitly, so one `std::string_view` parameter accepts a literal, a `std::string`, a substring or a slice of a raw buffer, and none of those calls allocates; a `const std::string&` parameter, by contrast, makes the caller build a temporary `std::string` from a literal. Pass it **by value**: it is two machine words and trivially copyable (required since C++23), so on the x86-64 System V and AArch64 ABIs it travels in two registers, while `const std::string_view&` adds a load through a pointer for no benefit. The price of the convenience is that a view is not null-terminated, converting back to `std::string` is explicit and copies, and the caller must keep the characters alive.

code

cpp · 27 lines
cpp
#include <cstdlib>
#include <iostream>
#include <new>
#include <string>
#include <string_view>

static int g_allocs = 0;
void* operator new(std::size_t n) {
    ++g_allocs;
    if (void* p = std::malloc(n)) return p;
    throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

bool is_json_ref(const std::string& v) { return v.find("application/json") == 0; }
bool is_json_view(std::string_view v) { return v.starts_with("application/json"); }

int main() {
    g_allocs = 0;
    bool a = is_json_ref("application/json; charset=utf-8");   // builds a temporary std::string
    std::cout << "const std::string&: " << g_allocs << " allocation(s)\n";
    g_allocs = 0;
    bool b = is_json_view("application/json; charset=utf-8");  // pointer + length, no copy
    std::cout << "std::string_view:   " << g_allocs << " allocation(s)\n";
    return (a && b) ? 0 : 1;
}

go deeper

for a junior

Describe std::string_view as a pointer plus a length that borrows characters, and pass it by value.

for a middle

Compare it with const std::string&: no allocation for literals and substrings, but no terminator and an explicit copy back to std::string.

for a senior

Justify by-value passing from the ABI and aliasing, and spot functions where a view parameter forces copies further down.

for a principal

Decide where views belong in public APIs and how to roll them out without creating ambiguous overloads or hidden copies.

## What a string_view is `std::string_view` is an alias for `std::basic_string_view<char>`, added in C++17 in the header `<string_view>`. It describes a **constant, contiguous sequence of characters that something else owns**. In practice it holds two members: a pointer to the first character and a length. It never allocates, never frees and cannot write to the characters. Its member functions mirror the read-only half of `std::string`: `size()`, `operator[]`, `find`, `compare`, `substr`, iteration, and since C++20 `starts_with` and `ends_with`. The standard states that its member functions are constant time unless specified otherwise; searching is the obvious exception. ## How text gets into one | source | conversion | cost | |---|---|---| | string literal or `const char*` | implicit | computes the length once with `char_traits::length` | | `std::string` | implicit, through `std::string`'s conversion operator | constant: copies pointer and size | | pointer and length | `std::string_view(p, n)` | constant | | `std::string_view` to `std::string` | **explicit**: `std::string(sv)` | allocates and copies | Two details matter in interviews. The conversion back to `std::string` is explicit on purpose, so a copy is always visible in the code: passing a view to a function taking `const std::string&` does not compile until you write `std::string(sv)`. And since C++23, `std::string_view(nullptr)` no longer compiles because that constructor is deleted; a null `const char*` variable is still undefined behaviour, since the length would be computed from it. ## Why pass it by value - **It is small.** Two machine words, the same as a pointer plus a `size_t`. - **It is trivially copyable.** C++23 made that a requirement of the standard, so copying it is a plain copy of two words. - **It travels in registers.** On the x86-64 System V and AArch64 calling conventions used by Linux and macOS, a two-word trivially copyable struct is passed in two registers. Compiled with clang `-O2` for AArch64, `std::size_t by_value(std::string_view s) { return s.size(); }` is one register move, while the `const std::string_view&` version must first load the size through the pointer. - **No aliasing doubts.** A by-value view is the callee's own copy; a reference could in principle alias something the function modifies, which can block optimizations. The usual C++ habit of "pass class types by const reference" exists to avoid expensive copies; a view's copy is not expensive, so the habit does not apply. ## string_view versus const std::string& The two parameter types read the same text, but they accept different arguments at different costs: 1. **Literals.** With `const std::string&`, calling `is_json("application/json; charset=utf-8")` constructs a temporary `std::string`; with libc++, a counting allocator shows one allocation per call. The `std::string_view` version shows none. 2. **Substrings and raw buffers.** A view can refer to the middle of another string or a received network buffer; a `const std::string&` needs a real `std::string`, often a copy. 3. **The null terminator.** `const std::string&` guarantees `c_str()`; a view does not, so a function that forwards to a C API is better off taking `const std::string&` or `const char*`. 4. **Ownership.** Neither parameter owns the text during the call, but a function that wants to keep the text must copy it either way, and then a by-value `std::string` parameter that it moves from is the better choice. ## Views of literals and the sv suffix With `using namespace std::literals;`, the suffix `sv` builds a view straight from a literal, using the literal's real length rather than scanning for a terminator. That matters for embedded nulls: `"a\0b"sv.size()` is 3, while `std::string_view("a\0b").size()` is 1, because the `const char*` constructor stops at the first `'\0'`. Comparisons need no conversions at all: `sv == "Host"`, `sv == some_string` and `sv.find("\r\n")` all work on the borrowed characters without building a `std::string`. ## What a view does not promise - It does not keep the characters alive; the owner must outlive every use. - It does not track changes to the owner: if the owning `std::string` reallocates, the view dangles. - It is not null-terminated in general, even when it happens to view a whole `std::string`. Those three caveats are where every string_view bug comes from, and the reason the type is ideal as a parameter and risky anywhere longer-lived.

  • Why does passing a std::string_view to a function taking const std::string& fail to compile?
    The conversion from `std::string_view` to `std::string` is an `explicit` constructor, so it is not used for implicit conversions in a call. The design keeps the copy visible: you must write `f(std::string(sv))`, which allocates when the text is longer than the small-string buffer. The opposite direction, `std::string` to `std::string_view`, is implicit because it is cheap and cannot fail.
  • When is const std::string& still the better parameter type than std::string_view?
    When the function needs a null-terminated string, typically because it passes the text to a C API: with a view it would have to copy into a `std::string` first. Also when it forwards to other functions that take `const std::string&`, where a view would force a copy at each such call. Readers that only inspect the characters should take `std::string_view`.

A std::string_view is a bookmark that also records how many pages the passage runs: handing someone a copy of the bookmark costs nothing, and it is exactly as useful as the original, but it is not the book. It works only while the book stays on the shelf with its pages where they were.

  • Pass std::string_view by const reference to avoid copying it.
  • std::string_view copies the characters into its own small buffer.
  • A std::string_view converts back to std::string implicitly and for free.
  • Calling a const std::string& parameter with a literal never allocates.
  • std::string_view can modify the characters it refers to.