# Strings and string_view

> std::string owns a contiguous, always null-terminated buffer and invalidates like a vector. std::string_view is a non-owning pointer and length pair, not null-terminated, whose main hazard is outliving the thing it looks at.

- **Source:** C++ Atlas (https://cppatlas.com/topics/strings-and-string-view)
- **Track:** Containers and strings
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [basic.string] (https://eel.is/c++draft/basic.string), [string.require] (https://eel.is/c++draft/string.require), [string.access] (https://eel.is/c++draft/string.access), [string.capacity] (https://eel.is/c++draft/string.capacity), [string.cons] (https://eel.is/c++draft/string.cons), [string.view] (https://eel.is/c++draft/string.view), [string.view.cons] (https://eel.is/c++draft/string.view.cons), [char.traits] (https://eel.is/c++draft/char.traits)
- **cppreference links:** [std::basic_string](https://en.cppreference.com/w/cpp/string/basic_string), [std::basic_string::resize_and_overwrite](https://en.cppreference.com/w/cpp/string/basic_string/resize_and_overwrite), [std::basic_string_view](https://en.cppreference.com/w/cpp/string/basic_string_view), [std::char_traits](https://en.cppreference.com/w/cpp/string/char_traits)
- **Prerequisites:** iterator-invalidation, reference-binding-and-temporaries

## The one idea

`std::string` and `std::string_view` are two answers to different questions. A `string` answers "who owns these characters?" It owns a heap or inline buffer, frees it, and can grow it. A `string_view` answers "where are these characters?" It is a pointer and a length, nothing more, and it says nothing about how long the characters will stay there.

Everything else follows. A `string` behaves like a `vector<char>` with a terminator: contiguous, reallocating, invalidating. A `string_view` behaves like a borrowed reference that you can copy cheaply, slice for free, and accidentally leave dangling.

> **Mental model.** A `string` is a buffer you own. A `string_view` is a borrowed window onto someone else's buffer. Copy the window as much as you like, but the owner must outlive every use of it.

## What `std::string` guarantees

The characters are stored contiguously, so `&s[0] + n == &s[n]` for every valid `n`, and `data()` can be handed to any C API that wants a pointer and a length. Since C++11 the buffer is also always null-terminated: `data()` and `c_str()` are the same function, and `data()[size()]` is a valid read that yields `'\0'`. This is why `s[s.size()]` is legal for reading, and why `at(s.size())` still throws `std::out_of_range`.

```cpp
#include <string>

void demo() {
  const std::string s = "abc";
  char c = s[s.size()];       // OK: reads the terminator, c == '\0'
  // s.at(s.size());          // throws std::out_of_range
  // s[s.size() + 1];         // undefined behavior
  (void)c;
}
```

The terminator is yours to read, not to change. For the non-const `operator[]`, writing anything other than `'\0'` to position `size()` is undefined behavior. Embedded null characters are fine, but then `c_str()` is only a C string up to the first one.

> **Standardese.** [string.access] says `operator[]` with `pos == size()` returns a reference to an object with value `charT()`, and that modifying it to any other value is undefined behavior. [string.require] requires the range `[data(), data() + size()]` to be valid, with the terminator at the end.

### Small string optimization is practice, not promise

Every mainstream implementation stores short strings inside the `string` object itself, so no allocation happens for them. The thresholds differ. On this 64-bit machine, libstdc++ keeps up to 15 characters inline in a 32-byte object, and libc++ keeps up to 22 in a 24-byte object. The standard promises neither number, and it does not even mention the optimization. What it does promise is that `capacity()` is at least `size()`, and `reserve` and `shrink_to_fit` obey their usual rules.

The practical consequence is that "pointer into a short string" is a pointer into the string object. Move it, swap it, or let it be destroyed, and the pointer goes with it. Never reason that a short string is "safe" because it did not allocate; follow the invalidation rules instead.

### Invalidation

Pointers, references and iterators into a `string` can be invalidated by any standard function that takes the string by non-const reference (`std::swap`, `std::getline`, `operator>>`) and by calling any non-const member function except `operator[]`, `at`, `data`, `front`, `back` and the `begin`/`end` family. In practice that means growth, `insert`, `erase`, `clear` and `reserve` should all be assumed to invalidate. This is close to the rule for `vector`, and the topic on iterator invalidation covers the machinery.

## `resize_and_overwrite`, `npos` and the new queries

Before C++23, filling a string from a C API meant `s.resize(n)`, which writes `n` zero bytes, and then overwriting them. `resize_and_overwrite(count, op)` hands your callable a pointer to storage for `count` characters and uses the integer it returns as the new size. The characters in the buffer beyond what you had before are indeterminate, so you must write every one you report.

```cpp
#include <cstdio>
#include <string>

std::string format_int(int v) {
  std::string s;
  s.resize_and_overwrite(12, [v](char* p, std::size_t n) {
    // snprintf writes the digits and a terminator, and returns the length
    return static_cast<std::size_t>(std::snprintf(p, n + 1, "%d", v));
  });
  return s;
}
```

The callable must not throw, must not modify `p` or `count`, and must return a value in `[0, count]`. Returning a length that includes characters you never wrote is undefined behavior, because the string would read indeterminate values. Every iterator, pointer and reference into the string is invalidated, even if no reallocation happened.

`std::string::npos` is `static_cast<size_type>(-1)`, the largest value of the unsigned size type. Every `find` family function returns it on failure, and it doubles as "until the end" for a length argument, so `s.substr(pos)` is the same as `s.substr(pos, npos)`. The recurring bug is treating the result as a signed index:

```cpp
#include <string>

void idioms(const std::string& s) {
  if (s.find('/') != std::string::npos) { /* found */ }
  std::size_t i = s.find('/');
  std::size_t next = i + 1;  // 0 when i == npos: unsigned wraparound
  (void)next;
}
```

When you only need a yes or no, C++20 gave `starts_with` and `ends_with`, and C++23 gave `contains`, each taking a character, a `string_view` or a C string. They say what you mean without an `npos` comparison.

## What `std::string_view` is

A `string_view` holds a `const char*` and a length. It is trivially copyable, `constexpr` throughout, and constructing one never allocates or copies characters. It can be built from a `std::string`, from a C string (which costs a `strlen`), from a pointer and length, and since C++23 from any contiguous range of `char` through an explicit constructor. Constructing one from `nullptr` is deleted in C++23.

```cpp
#include <string>
#include <string_view>

void view_basics() {
  std::string s = "hello";
  std::string_view sv = s;        // no copy, points at s's buffer
  s[0] = 'J';                     // sv now sees "Jello"
  sv.remove_prefix(1);            // moves sv's start; s is untouched
  std::string_view tail = sv.substr(1);  // O(1), unlike std::string::substr
  (void)tail;
}
```

Two properties set it apart from a `string`. First, a view has no terminator of its own: `sv.data()[sv.size()]` is not guaranteed to be anything, and in a slice such as `sv.substr(0, 5)` the byte after the end is simply the next character of the original text. Passing `data()` to a function expecting a C string reads past the view, as the next example does.

```cpp
#include <cstdio>
#include <string_view>

void leak() {
  std::string_view whole = "hello world";
  std::string_view w = whole.substr(0, 5);
  std::printf("%s\n", w.data());  // prints "hello world", not "hello"
}
```

Second, it does not own. The characters belong to whatever the view was made from, and the view's lifetime must fit inside theirs.

> **Pitfall.** Initializing a view from an expression that creates a temporary string leaves the view dangling at the end of the full expression. `std::string_view sv = s + "x";` compiles, and every later use of `sv` is undefined behavior. Neither GCC nor Clang rejects it by default, though recent Clang warns about some forms, and constant evaluation catches it.

```cpp
#include <string>
#include <string_view>

std::string name();

void dangling() {
  std::string_view a = name();            // dangling: the temporary dies at the semicolon
  std::string s = "abc";
  std::string_view b = s + "x";           // dangling for the same reason
  std::string_view ok = s;                // fine while s lives and is not reallocated
  (void)a; (void)b; (void)ok;
}
```

A view also dangles when its owner is modified: `s += "more"` may reallocate and leave `ok` pointing at freed memory, which is the same invalidation rule as for pointers.

## Conversions and parameters

`std::string` converts to `std::string_view` implicitly, through a conversion operator on `string`. The other direction is explicit, through a constructor template on `string`. The asymmetry is about cost and honesty: the first conversion is free and cannot fail, while the second allocates and copies, and the language lets you hide neither.

```cpp
#include <string>
#include <string_view>

void takes_view(std::string_view);
void takes_string(const std::string&);

void conv(std::string s, std::string_view v) {
  takes_view(s);                    // implicit, free
  // std::string t = v;             // ill-formed: explicit constructor
  std::string t{v};                 // OK: allocates and copies
  s = v;                            // OK: assignment from a view is provided directly
  s += v;                           // OK
  // takes_string(v);               // ill-formed for the same reason as above
  takes_string(std::string(v));     // OK
}
```

That shapes how functions should take text. A parameter of type `const std::string&` forces a temporary `string` for every string literal and every view the caller holds, and that construction allocates once the text exceeds the small-string capacity. A `std::string_view` parameter accepts a `string`, a literal and a view with no allocation. Use `string_view` for read-only parameters, and keep `std::string` when the function stores the text, because storing a view stores a promise someone must keep.

A view parameter is wrong when the callee needs a terminator, as C APIs do. A `const std::string&` or `const char*` is the honest type there. It is also a trap to store a view in a member, unless the owner's lifetime is guaranteed to cover it.

There is no `operator+` between a view and a C string, so `sv + "c"` is ill-formed. C++26 adds overloads that accept one `string` and one `string_view` operand, but still nothing for two views.

## Literals and `char_traits`

The suffix `s` in `"abc"s` makes a `std::string`, and `sv` in `"abc"sv` makes a `std::string_view` whose length is known at compile time, so even a literal with embedded nulls keeps all its characters. Both live in `std::literals` and need a `using namespace std::literals;` or a more specific using-directive. Prefer `sv` for constants, because a `constexpr std::string_view` never allocates and can be used in constant expressions.

Both classes are really `basic_string<CharT, Traits, Allocator>` and `basic_string_view<CharT, Traits>`. `char_traits` supplies the character comparison, copy and length operations, which is why `std::string` and `std::u8string` are the same template with different parameters, and why a case-insensitive string is a different type, not a flag. Different traits mean different, non-interchangeable types.

## What to remember

- `string` owns and reallocates like `vector`; `string_view` is a non-owning pointer and length.
- Since C++11 `data()` and `c_str()` are the same, and `data()[size()]` is a readable `'\0'`; writing anything else there is undefined.
- Small string optimization is an implementation habit with different thresholds; rely on the invalidation rules, not on "short strings do not move".
- `resize_and_overwrite` (C++23) avoids zero-filling, but every reported character must be written and the callable must not throw.
- `find` returns `npos`, an unsigned maximum; adding one to it wraps to zero. Prefer `starts_with`, `ends_with` and `contains` for yes or no questions.
- A `string_view` is not null-terminated, and a view initialized from a temporary string, such as `s + "x"`, dangles at the end of the statement.
- `string` converts to `string_view` implicitly; the reverse is explicit, because it allocates.
- Take `string_view` for read-only text, `std::string` for text you keep, and a `const char*` or `const std::string&` when a terminator is required.

## Concept Map Outline

- **Strings and string_view:** An owning buffer versus a borrowed window onto characters.
  - **std::string guarantees:** Contiguous, null-terminated storage with vector-like growth and invalidation.
    - **Contiguous storage:** data() works with any pointer-and-length API.
    - **Null terminator (C++11):** data()[size()] is readable and equals the null character; writing another value is undefined.
    - **Invalidation:** Non-const members other than operator[], at, data, front, back and begin/end may invalidate.
  - **Small string optimization:** An implementation habit, not a standard promise.
    - **Inline short strings:** libstdc++ holds 15 chars, libc++ 22 on 64-bit; the standard names neither.
    - **Pointers move with object:** Pointers into a short string point into the string object itself.
  - **Modern string API:** Newer members that say what you mean.
    - **resize_and_overwrite (C++23):** Skips zero-fill; every character you report must be written, and the callable must not throw.
    - **npos idioms:** npos is the unsigned maximum, so npos + 1 wraps to zero.
    - **starts_with, contains:** C++20 starts_with and ends_with, C++23 contains, avoid npos comparisons.
  - **std::string_view:** A non-owning pointer and length.
    - **Not null-terminated:** data()[size()] is not guaranteed; slices continue into the original text.
    - **Cheap slicing:** substr, remove_prefix and remove_suffix are O(1) and copy nothing.
    - **Dangling from temporaries:** A view built from s + "x" outlives the temporary and is undefined to read.
    - **Borrowed range:** A string_view is both a view and a borrowed range.
  - **Conversions and parameters:** Implicit one way, explicit the other.
    - **string to view implicit:** A conversion operator on string; free and cannot fail.
    - **view to string explicit:** A constructor that allocates; assignment and += from a view still work.
    - **Choosing parameter types:** string_view for read-only text, string to store it, const char* if terminator needed.
  - **Literals and traits:** Suffixes and the template behind the names.
    - **"x"s and "x"sv:** The s suffix makes a string, sv a view with known length, in std::literals.
    - **char_traits:** Supplies comparison and copy; different traits give different types.
    - **No view + view:** There is no operator+ for two views; C++26 adds string and view mixes.

## Standardese Quiz Questions

### Question 1 [warmup] ([string.cons], [basic.string])

Which statement in `main` is ill-formed in C++23?

```cpp
#include <string>
#include <string_view>

void takes_view(std::string_view);

int main() {
  std::string s = "text";
  std::string_view v = s;
  takes_view(s);          // (1)
  std::string a{v};       // (2)
  std::string b = v;      // (3)
  s = v;                  // (4)
}
```

A. (1), because string to string_view needs a cast
B. (2), because the string constructor from a view is deleted
C. (3), because the constructor taking a view is explicit
D. (4), because string has no assignment from a view

**Answer (C):** (3), because the constructor taking a view is explicit

**Why:** `std::string` converts to `std::string_view` through a conversion operator, so (1) is fine. The constructor from a view-like object is `explicit`, so direct-initialization in (2) works but copy-initialization in (3) is rejected. Assignment from a view is provided as its own overload, which is why (4) compiles even though (3) does not.

### Question 2 [warmup] ([string.view], [string.require])

What does this program print?

```cpp
#include <iostream>
#include <string>
#include <string_view>

int main() {
  std::string t = "hello";
  std::string_view sv = t;
  t[0] = 'J';
  std::cout << sv << '\n';
}
```

A. `hello`, because the view copied the characters
B. `Jello`
C. Undefined behavior, because the string was modified while a view existed
D. The program is ill-formed

**Answer (B):** `Jello`

**Why:** A `string_view` is a pointer and a length into `t`; it copies nothing. Writing through `operator[]` neither reallocates nor invalidates anything, so the view simply observes the new character. The view would only be at risk if `t` were modified in a way that can reallocate.

### Question 3 [warmup] ([string.capacity], [basic.string])

What does this program print?

```cpp
#include <iostream>
#include <string>

int main() {
  std::string s = "abc";
  std::size_t i = s.find('z');
  std::cout << (i + 1) << '\n';
}
```

A. `0`
B. `-1`
C. `4`
D. Undefined behavior

**Answer (A):** `0`

**Why:** `find` returns `std::string::npos`, which is `static_cast<size_type>(-1)`. `size_type` is unsigned, so adding one wraps around to zero, and unsigned wraparound is well-defined. The value `-1` is not representable in an unsigned type, which rules out the second option.

### Question 4 [tricky] ([string.view], [string.view.cons])

What does this program print?

```cpp
#include <cstdio>
#include <string_view>

int main() {
  std::string_view whole = "hello world";
  std::string_view w = whole.substr(0, 5);
  std::printf("%s\n", w.data());
}
```

A. `hello`
B. `hello world`
C. Undefined behavior, because `w.data()` is not null-terminated
D. Unspecified: it depends on the implementation

**Answer (B):** `hello world`

**Why:** `w` points into the same literal as `whole`, and `data()` returns that pointer without any terminator being added at the end of the slice. `printf` reads until the next `'\0'`, which is the literal's own terminator, so the whole text is printed. The read is well-defined here only because the underlying array is null-terminated; a view onto an unterminated buffer would read out of bounds.

### Question 5 [tricky] ([string.access])

What does this program print?

```cpp
#include <iostream>
#include <string>

int main() {
  const std::string s = "abc";
  std::cout << (s[s.size()] == '\0') << ' ';
  try {
    (void)s.at(s.size());
    std::cout << "no throw";
  } catch (const std::out_of_range&) {
    std::cout << "out_of_range";
  }
  std::cout << '\n';
}
```

A. `0 out_of_range`
B. Undefined behavior from `s[s.size()]`
C. `1 out_of_range`
D. `1 no throw`

**Answer (C):** `1 out_of_range`

**Why:** Since C++11, `operator[]` accepts `pos == size()` and returns a reference to the terminating `charT()`, so the comparison is true. `at` still checks `pos < size()` and throws `std::out_of_range`. Only `pos > size()` for `operator[]` is undefined, and writing a non-null value through the non-const version at `size()` is undefined too.

### Question 6 [tricky] ([class.temporary], [string.view])

What can be said about the second line of `use`?

```cpp
#include <iostream>
#include <string>
#include <string_view>

void use(const std::string& s) {
  std::string_view sv = s + "x";
  std::cout << sv << '\n';
}
```

A. It prints `s` followed by `x`, because the view extends the temporary's lifetime
B. Undefined behavior: the string temporary is destroyed at the end of the first line
C. It does not compile, because `string_view` cannot be built from a temporary
D. Well-defined only for strings short enough for small string optimization

**Answer (B):** Undefined behavior: the string temporary is destroyed at the end of the first line

**Why:** `s + "x"` creates a temporary `std::string`, and a conversion to `string_view` binds no reference, so lifetime extension does not apply. The temporary dies at the end of the full expression and `sv` then points into destroyed storage. Small string optimization does not help: the string object itself is the destroyed thing, and the standard says nothing that would make reading it valid.

### Question 7 [standardese] ([string.cons], [string.view.cons])

In C++23, what is the status of `std::string s(nullptr);`?

```cpp
#include <string>

int main() {
  std::string s(nullptr);
}
```

A. Undefined behavior, as for a null `const char*`
B. Well-formed, and `s` is empty
C. Implementation-defined
D. Ill-formed: the constructor taking `nullptr_t` is deleted

**Answer (D):** Ill-formed: the constructor taking `nullptr_t` is deleted

**Why:** C++23 (P2166) added `basic_string(nullptr_t) = delete`, so the call is diagnosed at compile time. Before that, `nullptr` converted to `const char*` and the call was undefined behavior because the pointer was not a valid null-terminated string. The same deletion exists for `basic_string_view`.

### Question 8 [standardese] ([string.capacity])

In C++23, what does the standard say about this call?

```cpp
#include <string>

int main() {
  std::string s;
  s.resize_and_overwrite(16, [](char* p, std::size_t n) {
    p[0] = 'a';
    p[1] = 'b';
    return n;
  });
}
```

A. `s` has size 16; the last 14 characters are value-initialized
B. `s` has size 2, because only two characters were written
C. Undefined behavior: the callable reported 16 characters but wrote only 2
D. Ill-formed, because the callable must return `void`

**Answer (C):** Undefined behavior: the callable reported 16 characters but wrote only 2

**Why:** `resize_and_overwrite` makes the string exactly as long as the integer the callable returns, and the characters of that range must all hold determinate values. The buffer beyond the old contents is indeterminate, and the callable wrote only two of the 16 it reported, so the string would hold indeterminate characters. The size is taken from the return value, never inferred from what was written, and the callable returns the new size, not `void`.
