Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 2 – Types, values and expressions

std::string and std::string_view

Build, change and search text with std::string, pass it cheaply as std::string_view, and catch the views that outlive their text before they print garbage.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Create, modify and search strings
  • Convert bytes to unsigned char before passing them to the <cctype> functions
  • Pass read-only text efficiently with std::string_view
  • Predict which strings are stored inside the object and which allocate
  • Avoid string_views that outlive the text they point to

Before you start

What you’ll learn · Before you start

What you will learn

  • Create, modify and search strings
  • Convert bytes to unsigned char before passing them to the <cctype> functions
  • Pass read-only text efficiently with std::string_view
  • Predict which strings are stored inside the object and which allocate
  • Avoid string_views that outlive the text they point to

Before you start

On this page

Splitting one line into 3 fields took 4 heap allocations as std::string and 1 as std::string_view in a GCC build. std::string owns a sequence of characters: it allocates the memory, grows it as you append, and frees it when the string is destroyed, so it is the type for text you build, change or keep. std::string_view (C++17) owns nothing: it is a pointer and a length that refer to characters someone else owns, so making one, or taking a piece of one, copies nothing.

That makes std::string_view the usual type for a function parameter that only reads text: it accepts a std::string, a string literal or a part of either without a copy. The price is lifetime. A view that outlives its text points at freed memory, and the compiler usually says nothing. Below, on Apple clang 21 and GCC 16, the savings are measured, each library’s short-string storage recorded and the dangling view: A std::string_view, or another view that owns nothing, whose characters have been destroyed or freed. Reading it is undefined behaviour, which AddressSanitizer reports as a heap-use-after-free when the characters were on the heap. reproduced under sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan”.

A std::string owns its characters and changes them in place

A std::string behaves like a value: copying it copies the characters, and comparing two strings compares their characters. The common operations, one per line:

editing.cpp C++
// Building and changing a std::string: the string owns its characters and grows as needed.
#include <print>
#include <stdexcept>
#include <string>

int main() {
    std::string order = "masala dosa";
    order += ", filter coffee";              // append
    order.insert(0, "2 x ");                 // insert at a position
    std::println("{} ({} characters)", order, order.size());

    order.replace(0, 1, "3");                // replace 1 character at position 0
    order.erase(order.find(','));            // erase from the comma to the end
    std::println("{}", order);

    const std::string item = order.substr(4, 6);  // a new string: 6 characters from position 4
    std::println("item = {}, first letter = {}, last letter = {}", item, item[0], item.back());

    try {
        std::println("{}", item.at(10));     // at() checks the position; item[10] would not
    } catch (const std::out_of_range&) {
        std::println("at(10) threw std::out_of_range");
    }
    const bool apple_first = std::string("apple") < std::string("banana");
    std::println("{}", apple_first ? "apple sorts first" : "banana sorts first");
}
Appending, inserting, replacing, erasing and slicing Python · editing_session.py
from session import run

run("""
clang++ --version | head -n 1
clang++ -std=c++23 -Wall -Wextra editing.cpp -o editing && ./editing
g++-16 --version | head -n 1
g++-16 -std=c++23 -Wall -Wextra editing.cpp -o editing && ./editing
""")

Output

$ clang++ --version | head -n 1
Apple clang version 21.0.0 (clang-2100.3.34.2)
$ clang++ -std=c++23 -Wall -Wextra editing.cpp -o editing && ./editing
2 x masala dosa, filter coffee (30 characters)
3 x masala dosa
item = masala, first letter = m, last letter = a
at(10) threw std::out_of_range
apple sorts first
$ g++-16 --version | head -n 1
g++-16 (Homebrew GCC 16.2.0) 16.2.0
$ g++-16 -std=c++23 -Wall -Wextra editing.cpp -o editing && ./editing
2 x masala dosa, filter coffee (30 characters)
3 x masala dosa
item = masala, first letter = m, last letter = a
at(10) threw std::out_of_range
apple sorts first

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 editing_session.py

  • += appends, insert(pos, text) inserts before position pos, replace(pos, count, text) replaces count characters, and erase(pos) removes everything from pos to the end.
  • find returns the position of the first match (here the comma), which is how erase knew where to start.
  • substr(pos, count) returns a new string with a copy of those characters.
  • s[i] does not check i: a position past the end is undefined behaviour: What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level. More in “Object lifetime and undefined behaviour in C++”. s.at(i) checks and throws std::out_of_range, as the output shows. front() and back() give the first and last character.
  • <, == and the other comparisons compare character by character, so "apple" sorts before "banana".

The program also shows that size() counts characters of type char, 30 for the order; the next lesson explains why that is a count of bytes, not of letters, once text is not plain English.

Step through order from its first value through the five calls on it, and watch the characters it holds after each one:

Interactive · stage by stage One order string through the five calls of editing.cpp Step through the program. After its first value, each stage is one call on order, and its sub-label shows the characters the string holds once the call is done.
One order string through the five calls of editing.cpp, step 6 of 6. Showing std::string order, += ", filter coffee" (masala dosa, filter coffee), insert(0, "2 x ") (2 x masala dosa, filter coffee), replace(0, 1, "3") (3 x masala dosa, filter coffee), erase(find(',')) (3 x masala dosa), substr(4, 6) (item = masala, a copy). In focus: substr(4, 6).std::string ordermasala dosa+= ", filter coffee"masala dosa, filter coffeeinsert(0, "2 x ")2 x masala dosa, filter coffeereplace(0, 1, "3")3 x masala dosa, filter coffeeerase(find(','))3 x masala dosasubstr(4, 6)item = masala, a copy

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The first value. order starts as masala dosa, 11 characters that the std::string owns: it allocated room for them, and it frees that room when it is destroyed.
  2. Appending. += adds ", filter coffee" at the end. The string makes room by itself whenever the characters no longer fit in what it holds.
  3. Inserting. insert(0, "2 x ") puts four characters before position 0, so every character after them moves along. The program printed the order with its size, 30 characters.
  4. Replacing. replace(0, 1, "3") takes the 1 character at position 0, the 2, and puts 3 in its place.
  5. Erasing. find(',') gives the position of the comma, 15, and erase(15) removes everything from there to the end. The program printed 3 x masala dosa.
  6. A new string. substr(4, 6) copies the 6 characters from position 4 into a new std::string: item = masala. Changing order now would leave item as it is.

Only the last call made a second string. Every other call changed order itself, which is what owning its characters allows.

Key idea

A std::string owns its characters, so it can grow, shrink and change them in place; of the calls above, only substr makes a new string.

Checkpoint

Check: A std::string owns and edits its text

  1. Question 1 of 2 What does s hold after these lines?

    Read the code, then choose one answer.

    std::string s = "idli";
    s += " vada";
    s.insert(0, "2 ");
    s.erase(s.find(' '), 1);
    A hint

    Write the string down after each line; erase with a count removes only that many characters.

    Show the answer: Question 1 of 2

    Answer: 2idli vada

    += appends, insert(0, …) puts text in front, and erase(pos, count) removes count characters from pos: the string goes idli, idli vada, 2 idli vada, 2idli vada.

  2. Question 2 of 2 const std::string item = "masala"; has 6 characters. What do item.at(10) and item[10] do?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: at(10) throws std::out_of_range; item[10] is undefined behaviour

    editing.cpp printed at(10) threw std::out_of_range. Use at() when a position may be out of range, and [] when you have already checked it.

The <cctype> functions need unsigned char values

Real input arrives with stray spaces and mixed case. normalise trims both ends, turns ASCII letters into lower case and collapses each run of spaces and tabs into one space:

normalise.cpp C++
// A name normaliser: trims the ends, lower-cases ASCII letters
// and collapses runs of spaces into one.
#include <cctype>
#include <print>
#include <string>
#include <string_view>

std::string normalise(std::string_view text) {
    std::string out;
    out.reserve(text.size());
    bool pending_space = false;
    for (char c : text) {
        // <cctype> functions need an unsigned char value:
        // passing a negative char is undefined behaviour.
        const auto u = static_cast<unsigned char>(c);
        if (std::isspace(u)) {
            pending_space = !out.empty();  // remember a gap, but never at the start
            continue;
        }
        if (pending_space) out += ' ';
        pending_space = false;
        out += static_cast<char>(std::tolower(u));
    }
    return out;
}

int main() {
    for (std::string_view raw : {"  Aditi   RAO ", "MEERA\tnair", "x", "   "}) {
        std::println("[{}] -> [{}]", raw, normalise(raw));
    }
}
Normalising four inputs Python · normalise_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra normalise.cpp -o normalise && ./normalise
g++-16 -std=c++23 -Wall -Wextra normalise.cpp -o normalise && ./normalise
""")

Output

$ clang++ -std=c++23 -Wall -Wextra normalise.cpp -o normalise && ./normalise
[  Aditi   RAO ] -> [aditi rao]
[MEERA	nair] -> [meera nair]
[x] -> [x]
[   ] -> []
$ g++-16 -std=c++23 -Wall -Wextra normalise.cpp -o normalise && ./normalise
[  Aditi   RAO ] -> [aditi rao]
[MEERA	nair] -> [meera nair]
[x] -> [x]
[   ] -> []

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 normalise_session.py

std::isspace and std::tolower come from C, and they take their argument as an int that must be a value of unsigned char (or EOF); anything else is undefined behaviour, says section 7.4 of the C standard. Every byte of a non-ASCII UTF-8 letter is above 127, and where char is signed, as it is on this Mac, such a byte is stored as a negative char, so the code converts each char to unsigned char first. out.reserve(text.size()) allocates once, since the result is never longer than the input.

This program prints the two bytes of é both ways:

The two bytes of é as char and as unsigned char C++ · signed_bytes.cpp
// The two bytes of é in UTF-8, read as a plain char and as an unsigned char.
// Plain char is signed on this Mac, so a byte above 127 becomes a negative number.
#include <print>
#include <string_view>

int main() {
    const std::string_view e_acute = "é";  // é: the bytes C3 A9
    for (const char c : e_acute) {
        const auto u = static_cast<unsigned char>(c);
        std::println("byte {:02X}: as char {}, as unsigned char {}", u, static_cast<int>(c), static_cast<int>(u));
    }
}

Output

byte C3: as char -61, as unsigned char 195
byte A9: as char -87, as unsigned char 169

Recorded with Apple clang version 21.0.0 (clang-2100.3.34.2) on macOS 26 arm64. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined signed_bytes.cpp -o signed_bytes && ./signed_bytes

As a char, the bytes C3 and A9 are -61 and -87, values std::isspace is not defined for; as unsigned char they are 195 and 169, which it is. Both compilers printed the same, because plain char is signed in both builds.

Passing a char straight to a <cctype> function

std::tolower(c) with a char from UTF-8 text passes -61 for the first byte of é. Write std::tolower(static_cast<unsigned char>(c)), as normalise does, so every byte reaches the function as a value from 0 to 255.

Checkpoint

Check: <cctype> and unsigned char

  1. Question 1 of 2 Plain char is signed on this Mac. The first byte of é in UTF-8 is 0xC3, which is 195. What value does it have as a char?

    Type a number.

    A hint

    A signed char holds -128 to 127; a byte above 127 wraps round by 256.

    Show the answer: Question 1 of 2

    Answer: -61

    195 - 256 = -61, as signed_bytes.cpp printed: byte C3: as char -61, as unsigned char 195. Passing -61 to std::isspace is undefined behaviour; passing 195 is correct.

  2. Question 2 of 2 Why does normalise convert each char to unsigned char before it calls std::isspace and std::tolower?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Every byte of a non-ASCII UTF-8 letter is above 127, a negative value in a signed char, and the <cctype> functions take only unsigned char values or EOF

    The cast costs nothing and turns every byte into a value from 0 to 255, which is exactly what the <cctype> functions are defined for.

find gives a position; the newer searches give true or false

find returns the position of the first match, rfind of the last, and both return std::string::npos, the largest value of std::size_t, when there is no match. C++20 and C++23 added three functions that answer the usual yes-or-no questions directly:

search.cpp C++
// Searching a string: find gives a position or npos;
// contains, starts_with and ends_with give a bool.
#include <print>
#include <string>

int main() {
    const std::string file = "report-q3-final.pdf";

    const auto dash = file.find('-');
    const auto zip = file.find(".zip");
    std::println("first '-' at {}, last '-' at {}", dash, file.rfind('-'));
    std::println("\".zip\" {}", zip == std::string::npos ? "not found (npos)" : "found");

    std::println("contains(\"final\"): {}", file.contains("final"));         // C++23
    std::println("starts_with(\"report\"): {}", file.starts_with("report"));  // C++20
    // C++20, and case matters
    std::println("ends_with(\".PDF\"): {}", file.ends_with(".PDF"));
}
Five searches Python · search_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra search.cpp -o search && ./search
g++-16 -std=c++23 -Wall -Wextra search.cpp -o search && ./search
""")

Output

$ clang++ -std=c++23 -Wall -Wextra search.cpp -o search && ./search
first '-' at 6, last '-' at 9
".zip" not found (npos)
contains("final"): true
starts_with("report"): true
ends_with(".PDF"): false
$ g++-16 -std=c++23 -Wall -Wextra search.cpp -o search && ./search
first '-' at 6, last '-' at 9
".zip" not found (npos)
contains("final"): true
starts_with("report"): true
ends_with(".PDF"): false

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 search_session.py

contains (C++23) replaces s.find(x) != std::string::npos, and starts_with and ends_with (C++20) replace comparisons with substr. All of them compare exactly, so ".PDF" does not match ".pdf".

The calls on "report-q3-final.pdf" and what each one gave back:

Call Result Type of the result
file.find('-') 6 std::size_t
file.rfind('-') 9 std::size_t
file.find(".zip") std::string::npos std::size_t
file.contains("final") true bool
file.starts_with("report") true bool
file.ends_with(".PDF") false bool

A position has to be compared with npos before it can be used; a bool answers the question as it stands, which is why the three newer functions read more plainly when a yes or a no is all you need.

Checkpoint

Check: find, contains, starts_with, ends_with

  1. Question 1 of 2 What does std::string("pune").find('z') return?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::string::npos, the largest value of std::size_t

    find and rfind return a position, or npos when there is no match. Test with != std::string::npos, or use contains when all you need is yes or no.

  2. Question 2 of 2 const std::string file = "Report-Q3.PDF"; Which test is true?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: file.starts_with("Report")

    contains, starts_with and ends_with compare characters exactly. For a case-blind test, lower-case both sides first, as normalise does for ASCII letters.

A view is a pointer and a length, so it copies nothing

A std::string_view holds two things: a pointer to the first character and a length. A function that takes one can be called with a string literal, a std::string or a view of part of either, and nothing is copied. substr on a view makes another view, so splitting a line into fields allocates nothing. The program below proves it by counting every heap allocation, through its own operator new:

views.cpp C++
// std::string_view refers to characters that someone else owns:
// making a view, or a piece of one, copies nothing.
// This program counts heap allocations to show it.
#include <cstdlib>
#include <new>
#include <print>
#include <string>
#include <string_view>
#include <vector>

static int allocations = 0;

// Every new and delete in the program goes through these two functions, so they can count.
void* operator new(std::size_t size) {
    ++allocations;
    if (void* p = std::malloc(size == 0 ? 1 : size)) 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); }

// The same splitter twice: the first returns copies, the second views into the original text.
std::vector<std::string> split_copies(const std::string& text, char sep) {
    std::vector<std::string> out;
    out.reserve(8);
    for (std::size_t start = 0;;) {
        const auto end = text.find(sep, start);
        out.push_back(text.substr(start, end - start));  // substr allocates when the piece is long
        if (end == std::string::npos) return out;
        start = end + 1;
    }
}

std::vector<std::string_view> split_views(std::string_view text, char sep) {
    std::vector<std::string_view> out;
    out.reserve(8);
    for (std::size_t start = 0;;) {
        const auto end = text.find(sep, start);
        out.push_back(text.substr(start, end - start));  // a string_view's substr never allocates
        if (end == std::string_view::npos) return out;
        start = end + 1;
    }
}

int main() {
    const std::string line = "Mumbai Central to New Delhi,Rajdhani Express number twelve,departs in the evening";

    allocations = 0;
    const auto copies = split_copies(line, ',');
    std::println("{} fields as std::string:      allocations = {}", copies.size(), allocations);

    allocations = 0;
    const auto views = split_views(line, ',');
    std::println("{} fields as std::string_view: allocations = {}", views.size(), allocations);
    std::println("first field: {}", views[0]);
}
Counting heap allocations while splitting a line Python · views_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra views.cpp -o views && ./views
g++-16 -std=c++23 -Wall -Wextra views.cpp -o views && ./views
""")

Output

$ clang++ -std=c++23 -Wall -Wextra views.cpp -o views && ./views
3 fields as std::string:      allocations = 3
3 fields as std::string_view: allocations = 1
first field: Mumbai Central to New Delhi
$ g++-16 -std=c++23 -Wall -Wextra views.cpp -o views && ./views
3 fields as std::string:      allocations = 4
3 fields as std::string_view: allocations = 1
first field: Mumbai Central to New Delhi

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 views_session.py

In both runs one allocation is the vector’s own storage (reserve(8)). With std::string, each field that is too long for the string’s inline buffer allocated too: two with libc++ (Apple clang) and three with libstdc++ (GCC), because “departs in the evening” has 22 characters, which fit inline in libc++ but not in libstdc++. With std::string_view, the fields cost nothing. The C++ Core Guidelines give the same advice (rule SL.str.2): refer to characters you do not own with std::string_view.

Step through both splits of the line and see where each of the three fields lives:

Interactive · step by step Where the three fields of one line live, as copies and as views Step through split_copies, then split_views. The left column is the line and the vector, the right one the three fields; an arrow means a field points into the line.
Where the three fields of one line live, as copies and as views, step 5 of 5. Showing line: 81 characters, the vector of fields (reserve(8): 1 allocation), field 1: 27 characters (a view, no copy), field 2: 30 characters (a view, no copy), field 3: 22 characters (a view, no copy). In focus: the vector of fields, line: 81 characters.+0, size 27+28, size 30+59, size 22line: 81 charactersone std::stringthe vector of fieldsreserve(8): 1 allocationfield 1: 27 charactersa view, no copyfield 2: 30 charactersa view, no copyfield 3: 22 charactersa view, no copy

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Copies of the first two. split_copies calls substr on a std::string, which copies each field into a new std::string. 27 and 30 characters are more than either inline buffer holds, so both fields allocate, on both libraries.
  2. The third copy. The last field has 22 characters. That fits inside a libc++ string, which holds up to 22, but not a libstdc++ one, which holds up to 15, so only the GCC build allocates for it.
  3. Counting the copies. With the vector's own storage, that is 3 allocations with libc++ (Apple clang) and 4 with libstdc++ (GCC), as the two runs printed.
  4. Views instead. split_views calls substr on a std::string_view, which makes another view: a pointer into line and a length. No character is copied; field 1 is line from position 0, 27 characters long.
  5. One allocation. Only the vector allocated: allocations = 1 on both libraries, and the first view printed Mumbai Central to New Delhi. The views are valid only while line is alive.

Each view is two numbers into line. The diagram shows the same picture for one view, word, into another text, and what is left of the view once that text is destroyed:

A std::string owns its characters on the heap; a std::string_view points into them, and dangles once the string is destroyed.std::string textpointer, size 37,capacitystd::string_view wordpointer, size 8on the heap:"Namaste, and welcometo the C++ track"text destroyed:word now pointsat freed memoryownspoints into

A std::string owns its characters; a std::string_view only points at them

Text description of the diagram

The diagram has four boxes.

  • At the top right is std::string text, which holds a pointer, its size, 37, and its capacity. An arrow labelled owns goes from it to the characters.
  • At the top left is std::string_view word, which holds only a pointer and a size, 8. An arrow labelled points into goes from it to the same characters.
  • In the middle are the characters on the heap: "Namaste, and welcome to the C++ track". The string allocated them and frees them in its destructor.
  • A dashed arrow leads down to the last box: once text is destroyed, word still points at the same place, which is now freed memory.

A view is not a string, and three differences matter:

  • It is read-only: there is no +=, insert or erase.
  • It need not end with a '\0'. view.data() points into someone else’s characters, so passing it to a C function that expects a null-terminated string: A sequence of characters followed by a zero byte, '\0', which is how C functions such as std::puts and std::fopen find its end. std::string::c_str() always gives one; std::string_view::data() need not. can read past the end; the standard says so in a note to data(). Convert with std::string(view) when you need a terminated copy.
  • It does not keep the characters alive. That is the section after the next one.

Key idea

A view is a pointer and a length into someone else’s characters: making one, or cutting a piece of one, costs nothing, and it can read them but never change or keep them.

Checkpoint

Check: A view is a pointer and a length

  1. Question 1 of 2 What does a std::string_view hold?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: A pointer to the first character and a length

    Two values, a pointer and a size: the diagram shows word as a pointer and a size of 8 into the characters of text.

  2. Question 2 of 2 split_views from views.cpp splits a line of 5 fields, each over 30 characters long. How many heap allocations does it make?

    Type a number.

    A hint

    Which object in split_views owns any memory?

    Show the answer: Question 2 of 2

    Answer: 1 allocations

    Only the vector allocates, once, for reserve(8); each field is a view into the line, whatever its length. With split_copies every field over the inline limit would allocate as well: 6 in all.

Small strings live inside the object

The standard does not say how a std::string stores its characters, but both libraries keep short strings inside the std::string object itself, which avoids an allocation; longer strings go on the heap. This is the small-string optimisation: Storing the characters of a short string inside the std::string object itself, so that no heap memory is allocated. The limit is the library's own: 22 characters with libc++ and 15 with libstdc++ in this track's 64-bit builds., and its limit differs:

sso.cpp C++
// Short strings are stored inside the std::string object itself; longer ones on the heap.
// How short is short depends on the standard library.
#include <cstdint>
#include <print>
#include <string>

// Whether the characters of s sit inside the bytes of the object s.
bool stored_inside(const std::string& s) {
    const auto object = reinterpret_cast<std::uintptr_t>(&s);
    const auto characters = reinterpret_cast<std::uintptr_t>(s.data());
    return characters >= object && characters < object + sizeof s;
}

int main() {
    std::println("sizeof(std::string) = {}, capacity of an empty string = {}", sizeof(std::string),
                 std::string{}.capacity());
    for (std::size_t length : {15, 16, 22, 23}) {
        const std::string s(length, 'x');
        std::println("{} characters: {}", length, stored_inside(s) ? "inside the object" : "on the heap");
    }
}
Where 15, 16, 22 and 23 characters are stored Python · sso_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra sso.cpp -o sso && ./sso
g++-16 -std=c++23 -Wall -Wextra sso.cpp -o sso && ./sso
""")

Output

$ clang++ -std=c++23 -Wall -Wextra sso.cpp -o sso && ./sso
sizeof(std::string) = 24, capacity of an empty string = 22
15 characters: inside the object
16 characters: inside the object
22 characters: inside the object
23 characters: on the heap
$ g++-16 -std=c++23 -Wall -Wextra sso.cpp -o sso && ./sso
sizeof(std::string) = 32, capacity of an empty string = 15
15 characters: inside the object
16 characters: on the heap
22 characters: on the heap
23 characters: on the heap

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sso_session.py

Standard library sizeof(std::string) Characters stored inside
libc++ (Apple clang 21) 24 bytes up to 22
libstdc++ (GCC 16) 32 bytes up to 15

Both are 64-bit builds on the same Mac. This explains the different allocation counts above, and it matters for the next example: a dangling view into a short string may still find the old characters in place, so a test with short text can hide the bug, while text longer than the inline buffer lives in heap memory that AddressSanitizer watches.

Checkpoint

Check: Short strings inside the object

  1. Question 1 of 2 Where are the characters of a 20-character std::string, built with each standard library on this Mac?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Inside the object with libc++ (Apple clang), on the heap with libstdc++ (GCC)

    sso.cpp recorded the limits: 22 characters inside a 24-byte libc++ string and 15 inside a 32-byte libstdc++ one. The standard fixes neither number.

  2. Question 2 of 2 A test should let AddressSanitizer catch a dangling view of a std::string on both standard libraries. How long should its text be?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 23 characters or more

    Short text can hide the bug because it never leaves the string object. Text longer than the inline buffer of every library you build with lives on the heap, where the freed block is reported.

A view that outlives its string reads freed memory

Here are the two classic ways to create a dangling view. greeting() returns a view into its local string, which is destroyed when the function returns, and temporary.cpp keeps a view of a temporary object: An unnamed object made while an expression is evaluated, such as the std::string that city + ' Central' produces. It is destroyed at the end of the full expression that made it, unless a reference bound to it keeps it alive. string, which is destroyed at the end of the statement that made it:

Two dangling views

dangling.cpp

// A std::string_view must not outlive the string it looks at. Both mistakes below compile.
#include <print>
#include <string>
#include <string_view>

std::string_view first_word(std::string_view text) {
    return text.substr(0, text.find(' '));  // fine: a view into the caller's text
}

std::string_view greeting() {
    // longer than the small-string buffer
    const std::string local = "Namaste, and welcome to the C++ track";
    return first_word(local);  // a view into local, which is destroyed when greeting() returns
}

int main() {
    const std::string kept = "Vanakkam everyone";
    std::println("{}", first_word(kept));  // fine: kept is still alive

    const std::string_view word = greeting();
    std::println("{}", word);  // reads the memory of a destroyed string
}

temporary.cpp

// A view of a temporary string: the temporary is destroyed at the end of the line that made it.
#include <print>
#include <string>
#include <string_view>

int main() {
    const std::string city = "Thiruvananthapuram";
    std::string_view shout = city + " Central";  // city + " Central" is a temporary std::string
    std::println("{}", shout);
}
Both mistakes under AddressSanitizer Python · dangling_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined dangling.cpp -o dangling && ./dangling
g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined dangling.cpp -o dangling && ./dangling
clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined temporary.cpp -o temporary && ./temporary
g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined temporary.cpp -o temporary && ./temporary
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined dangling.cpp -o dangling && ./dangling
Vanakkam
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
    #28 in main dangling.cpp:21
0x… is located 0 bytes inside of 40-byte region [0x…,0x…)
freed by thread T0 here:
    #2 in greeting() dangling.cpp:14
    #3 in main dangling.cpp:20
previously allocated by thread T0 here:
    #4 in greeting() dangling.cpp:12
    #5 in main dangling.cpp:20
SUMMARY: AddressSanitizer: heap-use-after-free
[73 more lines of the report left out]
[exit status 134]
$ g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined dangling.cpp -o dangling && ./dangling
Vanakkam
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 8 at 0x… thread T0
    #8 in main dangling.cpp:21
0x… is located 0 bytes inside of 38-byte region [0x…,0x…)
freed by thread T0 here:
    #5 in greeting() dangling.cpp:14
    #6 in main dangling.cpp:20
previously allocated by thread T0 here:
    #6 in greeting() dangling.cpp:12
    #7 in main dangling.cpp:20
SUMMARY: AddressSanitizer: heap-use-after-free
[58 more lines of the report left out]
[exit status 134]
$ clang++ -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined temporary.cpp -o temporary && ./temporary
temporary.cpp:8:30: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
    8 |     std::string_view shout = city + " Central";  // city + " Central" is a temporary std::string
      |                              ^~~~~~~~~~~~~~~~~
1 warning generated.
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 26 at 0x… thread T0
    #28 in main temporary.cpp:9
0x… is located 0 bytes inside of 32-byte region [0x…,0x…)
freed by thread T0 here:
    #2 in main temporary.cpp:8
previously allocated by thread T0 here:
    #12 in main temporary.cpp:8
SUMMARY: AddressSanitizer: heap-use-after-free
[81 more lines of the report left out]
[exit status 134]
$ g++-16 -std=c++23 -Wall -Wextra -g -fsanitize=address,undefined temporary.cpp -o temporary && ./temporary
=================================================================
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 26 at 0x… thread T0
    #8 in main temporary.cpp:9
0x… is located 0 bytes inside of 31-byte region [0x…,0x…)
freed by thread T0 here:
    #5 in main temporary.cpp:8
previously allocated by thread T0 here:
    #7 in main temporary.cpp:8
SUMMARY: AddressSanitizer: heap-use-after-free
[59 more lines of the report left out]
[exit status 134]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 dangling_session.py

AddressSanitizer stops all four runs with a heap-use-after-free report that names the line that read the memory, the line that freed it and the line that allocated it (the sessions keep those lines of each report and write the addresses, which change on every run, as 0x…). The compilers are less helpful:

  • Clang warns about the temporary (-Wdangling-gsl, on by default); GCC 16 says nothing.
  • Neither compiler warns about the view returned from greeting(), because it passes through first_word, a function that is fine on its own. Clang does warn (-Wreturn-stack-address) when a function returns its local string directly as a view, return local;, but one function call in between is enough to hide it.

Step through dangling.cpp in time order and watch where word points when line 21 reads it:

Interactive · message by message How word in dangling.cpp ends up pointing at freed memory Step through the calls in time order. The columns are main, the function greeting() and the heap memory that local's characters live in; each arrow is one thing that happens.
How word in dangling.cpp ends up pointing at freed memory, step 6 of 6. Messages so far: main to greeting(): greeting(); greeting() to heap memory: allocate 37 characters; greeting() to main: return the view; greeting() to heap memory: free the block; main to heap memory: print word: 8 bytes.mainword: a string_viewgreeting()local: a std::stringheap memorylocal's charactersgreeting()allocate 37 charactersreturn the viewfree the blockprint word: 8 bytesfreed: heap-use-after-free

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The call. After printing Vanakkam from a string that is still alive, main calls greeting() on line 20 to set word.
  2. local allocates. local holds "Namaste, and welcome to the C++ track", 37 characters, too many for either inline buffer, so line 12 allocates a block for them: 40 bytes with libc++, 38 with libstdc++.
  3. A view of the first word. first_word(local) returns text.substr(0, text.find(' ')): a view of Namaste, with the comma, a pointer into the heap block and the size 8. first_word itself is correct.
  4. The view goes back. greeting() returns that view to main, which stores it in word. A view copies a pointer and a length, never the characters.
  5. local is destroyed. As greeting() returns, its local string is destroyed, and its destructor frees the heap block: line 14 in the report. word still points at the first byte of it.
  6. Reading freed memory. Line 21 prints word, a read of 8 bytes in the freed block. AddressSanitizer stopped both builds there with a heap-use-after-free that names lines 21, 14 and 12, while neither compiler had warned.

No single line is wrong: first_word is correct, and so is greeting until it returns. The bug is that word lives longer than local.

So the rules are about lifetimes, not syntax. Return a std::string from a function that builds text; take a std::string_view parameter only for text you read during the call; store a std::string in a variable or a member that must outlive the call; and run tests with -fsanitize=address, using text longer than the inline buffer.

Character Counter Count characters, UTF-8 bytes and lines of any text, to see how long a string really is.

Checkpoint

Check: Views that outlive their text

  1. Question 1 of 2 Which of the three functions returns a view that dangles?

    Read the code, then choose one answer.

    std::string_view a() { return "chai"; }
    std::string_view b() {
        const std::string s = "chai and samosa for two";
        return s;
    }
    std::string_view c(const std::string& s) { return s; }
    Show the answer: Question 1 of 2

    Answer: b

    The question is always what owns the characters and how long it lives: a literal lives forever, the caller's string as long as the caller keeps it, and a local only until the function returns.

  2. Question 2 of 2 Which compiler warned about temporary.cpp, the view of city + " Central"?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Clang, with -Wdangling-gsl, which is on by default; GCC 16 said nothing

    Warnings catch some dangling views and miss others, such as the one in dangling.cpp that passed through first_word. AddressSanitizer caught all four runs.

Choose the type by who owns the text and how long it must live

Every rule of this lesson comes down to two questions: who owns the characters, and how long must they stay usable? Answer them for a parameter, a variable or a member of your own, and the table rules out the types that would break, with the program above that showed each failure:

Interactive · answer and compare std::string_view, const std::string& or std::string? Answer the questions about where the text is held, in a parameter, a variable, a member or a container. The table rules out the types that would break, with the reason, and marks the ones that cost a copy.
Must the text stay usable after the call, as a member, a return value, a container element or text a function keeps?
Does the text go to a C function that needs a terminating \0?
Is it made from string literals or from pieces of a longer text?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

Three types for text against literals, pieces, owning the characters and a terminating zero
Type A literal costs nothing A piece costs nothing Owns its characters Ends with a \0 for C
std::string_view Good f("a literal") builds no std::string at all Good substr on a view copies nothing: 3 fields, 1 allocation in all Poor no: word read freed memory once local was destroyed Poor not promised: data() may run past the last character
const std::string& Poor a literal first becomes a temporary std::string Poor a piece must be copied into a std::string first Poor no: it refers to a string that someone else keeps alive Good yes: c_str() always ends with \0
std::string Mixed copies the literal, and allocates when it is long Mixed substr copies: 2 fields allocated with libc++, 3 with libstdc++ Good yes: it frees its characters only in its own destructor Good yes: c_str() always ends with \0
How the answers decide
  • “Must the text stay usable after the call, as a member, a return value, a container element or text a function keeps?” Yes, it is kept: rules out std::string_view. A view owns nothing: the one greeting() returned read freed memory once local was destroyed. Whatever keeps the text must own it, as a std::string does.
  • “Must the text stay usable after the call, as a member, a return value, a container element or text a function keeps?” Yes, it is kept: adds a caveat to const std::string&. const std::string& owns nothing either: it suits the parameter of a function that copies the text into a std::string it keeps, never the thing that is kept.
  • “Does the text go to a C function that needs a terminating \0?” Yes, a C function reads it: rules out std::string_view. A view need not end with \0, so a C function reading view.data() can run past its end; std::string(view) makes a terminated copy.
  • “Must the text stay usable after the call, as a member, a return value, a container element or text a function keeps?” No, it is read during the call and “Is it made from string literals or from pieces of a longer text?” Yes, literals or pieces: adds a caveat to const std::string& and std::string. Each literal or piece is first copied into a std::string, which allocates when the text is longer than the inline buffer: 22 characters with libc++, 15 with libstdc++.
  • “Must the text stay usable after the call, as a member, a return value, a container element or text a function keeps?” No, it is read during the call and “Does the text go to a C function that needs a terminating \0?” No: Text that is only read while its string exists is what std::string_view is for: literals, strings and pieces of either, with nothing copied.

In short: std::string_view for text a function reads during the call; std::string for text that is built, kept or must end with a zero for C; and const std::string& for a string the caller already has, when the function needs c_str() for C or copies the text into something it keeps.

Key idea

Own the text wherever it must outlive its source, and view it wherever it is only read: a view costs nothing until it outlives what it points at.

Checkpoint

Check: Choosing a type for text

  1. Question 1 of 2 Which parameter type lets count_words("a literal that is longer than thirty characters") run without creating any std::string?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: std::string_view

    That is the warm-up's answer in practice: a std::string_view parameter accepts literals, strings and pieces without a single allocation.

  2. Question 2 of 2 A function builds a greeting from a name, such as "Namaste, Asha", and hands it back. What should it return?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: std::string

    Return a std::string from a function that builds text. Returning it costs no copy in practice: the result is built in place or moved.

Practise: split and join

Write split, which cuts a std::string_view at every separator and returns the pieces as views into the original text (keeping empty pieces), and join, which glues pieces together with a separator between them. The checks in main must all print ok; the last one checks that split copies nothing.

split_join.cpp C++
// Exercise: write split and join. Build and run this file: every check must say "ok".
//   split("a,b,c", ',') gives the views {"a", "b", "c"}; empty fields are kept.
//   join({"a", "b", "c"}, ", ") gives the string "a, b, c".
#include <print>
#include <string>
#include <string_view>
#include <vector>

std::vector<std::string_view> split(std::string_view text, char separator) {
    (void)text;
    (void)separator;
    return {};  // replace this
}

std::string join(const std::vector<std::string_view>& parts, std::string_view separator) {
    (void)parts;
    (void)separator;
    return {};  // replace this
}

int failures = 0;

void check(bool passed, std::string_view what) {
    std::println("{}  {}", passed ? "ok    " : "FAILED", what);
    if (!passed) ++failures;
}

int main() {
    using Parts = std::vector<std::string_view>;
    check(split("idli,dosa,vada", ',') == Parts{"idli", "dosa", "vada"}, "three fields");
    check(split("chai", ',') == Parts{"chai"}, "no separator: one field");
    check(split("a,,b", ',') == Parts{"a", "", "b"}, "an empty field in the middle is kept");
    check(join({"idli", "dosa", "vada"}, ", ") == "idli, dosa, vada", "join with a separator");
    check(join({"chai"}, " + ") == "chai", "one part: no separator");

    const std::string line = "Pune;Nashik;Nagpur";
    const auto parts = split(line, ';');
    check(!parts.empty() && parts[0].data() == line.data(),
          "the views point into the original text (no copies)");
    std::println("{} of 6 checks failed", failures);
    return failures == 0 ? 0 : 1;
}

As given, every check fails:

The exercise as given Python · split_join_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined split_join.cpp -o split_join && ./split_join
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined split_join.cpp -o split_join && ./split_join
FAILED  three fields
FAILED  no separator: one field
FAILED  an empty field in the middle is kept
FAILED  join with a separator
FAILED  one part: no separator
FAILED  the views point into the original text (no copies)
6 of 6 checks failed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 split_join_session.py

First hint: loop with text.find(separator, start), and stop after the piece for which find returns npos. text.substr(start, end - start) gives the right piece even then, because substr stops at the end of the view.

Once all six checks pass, test yourself on the seven ideas. The session begins with the idea you have answered least well, and every option you pick says what it gets right or misses:

Practice that adapts to you

Practise this lesson

17 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 17 What does a hold after these lines?

    Read the code, then choose one answer.

    std::string a = "tea";
    std::string b = a;
    b += "!";
    Show the answer: Question 1 of 17

    Answer: tea

    Copying a std::string copies the characters, and comparing two strings compares their characters: the string behaves like an int would, only longer.

  2. Question 2 of 17 std::string order = "3 x masala dosa"; then std::string item = order.substr(4, 6); and order[4] = 'M';. What is item?

    Choose one answer.

    Show the answer: Question 2 of 17

    Answer: masala

    std::string::substr(pos, count) copies count characters from pos into a new std::string, as item = masala showed in editing.cpp.

  3. Question 3 of 17 Is std::string("Banana") < std::string("apple") true or false?

    Choose one answer.

    Show the answer: Question 3 of 17

    Answer: True, because B has a smaller character code than a

    apple sorts before banana in editing.cpp because both are lower case. To sort names as a dictionary would, compare them after lower-casing, for example with normalise.

  4. Question 4 of 17 c is a char from UTF-8 text. Which call is correct?

    Choose one answer.

    Show the answer: Question 4 of 17

    Answer: std::isspace(static_cast<unsigned char>(c))

    The <cctype> functions need a value of unsigned char (or EOF). Bytes of non-ASCII UTF-8 letters are above 127, so a signed char holds them as negative numbers, and passing those is undefined behaviour.

  5. Question 5 of 17 Which argument values may std::tolower be given?

    Choose one answer.

    Show the answer: Question 5 of 17

    Answer: Values that an unsigned char can hold, 0 to 255, or EOF

    The functions take an int so that they can accept EOF, but the values they are defined for are those of unsigned char.

  6. Question 6 of 17 Which edition of C++ added contains to std::string?

    Choose one answer.

    Show the answer: Question 6 of 17

    Answer: C++23

    Before C++20 the same questions were written as s.find(x) != std::string::npos and comparisons with substr.

  7. Question 7 of 17 What does this print?

    Read the code, then choose one answer.

    const std::string file = "notes.PDF";
    std::println("{} {}", file.ends_with(".pdf"), file.contains("PDF"));
    Show the answer: Question 7 of 17

    Answer: false true

    The comparisons are exact, so ".pdf" does not match ".PDF", while "PDF" is contained in the name. contains is C++23 and ends_with C++20.

  8. Question 8 of 17 Can you write view += "!"; for a std::string_view view?

    Choose one answer.

    Show the answer: Question 8 of 17

    Answer: No: a view is read-only, with no +=, insert or erase

    Views read; strings own and edit. That split is what makes a view cheap and a string safe to keep.

  9. Question 9 of 17 s is a long std::string and v is a std::string_view of it. Which expression copies characters?

    Choose one answer.

    Show the answer: Question 9 of 17

    Answer: s.substr(0, 30)

    std::string::substr returns a new std::string, which copies the characters and allocates when they do not fit inline. A view's substr and a conversion to std::string_view only make a new pointer and length.

  10. Question 10 of 17 What does the last line print?

    Read the code, then choose one answer.

    const std::string_view all = "chai and samosa";
    const std::string_view word = all.substr(0, 4);
    std::puts(word.data());
    A hint

    std::puts knows nothing of the view's size.

    Show the answer: Question 10 of 17

    Answer: chai and samosa

    This is why a view must not go to a C function that expects a terminated string: the standard's note to data() warns of exactly this. std::string(word).c_str() would print chai.

  11. Question 11 of 17 How many characters can a std::string hold inside the object itself with GCC 16's libstdc++, before it allocates?

    Type a number.

    Show the answer: Question 11 of 17

    Answer: 15

    The recorded run shows 15 for libstdc++ (the object is 32 bytes) and 22 for libc++, Apple clang's library (24 bytes). The standard does not fix either number.

  12. Question 12 of 17 The three fields of views.cpp have 27, 30 and 22 characters. How many of them fit inside a std::string with libc++, without an allocation?

    Type a number.

    Show the answer: Question 12 of 17

    Answer: 1 fields

    libc++ holds up to 22 characters inside the object, so only "departs in the evening" fits. That is why split_copies made 3 allocations with libc++ (2 fields and the vector) and 4 with libstdc++.

  13. Question 13 of 17 Which of these leave a std::string_view that dangles once the statement or function has finished?

    Choose every answer that is right.

    Show the answer: Question 13 of 17

    Answer:

    • returning std::string_view(local) from a function, where local is a local std::string
    • std::string_view a = std::string("abc") + "def";

    The temporary made by + is destroyed at the end of the statement, and a local string is destroyed when its function returns, so views of them dangle. A string literal lives for the whole program, and a view of s is fine as long as s lives.

  14. Question 14 of 17 In dangling.cpp, why does printing word read freed memory?

    Choose one answer.

    Show the answer: Question 14 of 17

    Answer: word views the characters of local, which greeting() destroyed when it returned

    The bug is a lifetime, not a line: every function is correct alone, and the view outlived the string it was made from.

  15. Question 15 of 17 std::string_view shout = city + " Central"; dangles. Which replacements make shout safe to print on the next line?

    Choose every answer that is right.

    Show the answer: Question 15 of 17

    Answer:

    • auto shout = city + " Central";
    • std::string shout = city + " Central";

    Only an owning type fixes it. auto works here because, as the previous lesson showed, it takes the type of the value, and the value of city + " Central" is a std::string.

  16. Question 16 of 17 What is the usual parameter type for a function that only reads text during the call?

    Choose one answer.

    Show the answer: Question 16 of 17

    Answer: std::string_view

    Read during the call: std::string_view. Keep after the call, or pass to a C API: a std::string.

  17. Question 17 of 17 A logger keeps every message it receives in a std::vector and writes them out at the end of the run. What should the vector hold?

    Choose one answer.

    Show the answer: Question 17 of 17

    Answer: std::string

    Text that is kept must be owned, so the vector holds std::string values. As the interview answer of this lesson says, a function that keeps text takes it as const std::string& or as a std::string.

Interview questions

Fresher · When should a function take std::string_view instead of const std::string&?

When it only reads the text during the call. A std::string_view parameter accepts string literals, std::string objects and parts of either without creating a temporary std::string, so a call such as f("literal") allocates nothing, and taking a piece costs nothing. Take const std::string& (or a std::string by value) when the function needs a terminated string for a C API, or keeps the text after it returns.

Interviewers then check that you know where the rule stops. Choose an answer to each follow-up below; every option explains what it gets right or misses:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: "The function now passes the text to std::fopen, which needs a terminated string. Do you keep the std::string_view parameter?"

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: No: take const std::string& and pass c_str(), because a view need not end with a '\0'

    The strong answer names the exception to the rule: views for text you only read, but a terminated string for a C API, either taken as const std::string& or made with std::string(view) at the one place that needs it.

  2. Question 2 of 2 Follow-up: "How many std::string objects does a call with a 40-character literal create, with each parameter type?"

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: One temporary for const std::string&, allocating on both libraries; none for std::string_view

    Counting what a call creates is the reason std::string_view exists: one temporary string, with one heap allocation, per call with a long literal, against none.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    A class stores a std::string_view member set from a constructor argument. Objects made from string literals work, but objects made from lines read in a loop print garbage later. Explain what happens and how you would fix the class.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A log parser splits each 300-byte line into 12 fields stored as std::string, at 50,000 lines a second, and a profile shows most of the time in malloc. How would you reduce the cost, and what new risk do you take on?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • std::string owns its characters; std::string_view is a pointer and a length into characters owned elsewhere, so substr on a std::string copies and on a std::string_view copies nothing, as the allocation counts show.
  • at() checks positions, [] does not; contains (C++23), starts_with and ends_with (C++20) replace find comparisons.
  • size() counts char values, which are bytes; pass them to std::isspace, std::tolower and the other <cctype> functions as unsigned char. The next lesson is about what bytes mean for Unicode text.
  • Short strings live inside the object: up to 22 characters with libc++, 15 with libstdc++.
  • A view must not outlive its text: never return a view of a local string or keep a view of a temporary; Clang warns about some cases, AddressSanitizer catches them at run time.
  • Take std::string_view for text you read during a call, and hold a std::string for text that is kept, built or passed to a C function.

Terms in this lesson

dangling view
A std::string_view, or another view that owns nothing, whose characters have been destroyed or freed. Reading it is undefined behaviour, which AddressSanitizer reports as a heap-use-after-free when the characters were on the heap.
null-terminated string
A sequence of characters followed by a zero byte, '\0', which is how C functions such as std::puts and std::fopen find its end. std::string::c_str() always gives one; std::string_view::data() need not.
small-string optimisation
Storing the characters of a short string inside the std::string object itself, so that no heap memory is allocated. The limit is the library's own: 22 characters with libc++ and 15 with libstdc++ in this track's 64-bit builds.
temporary object
An unnamed object made while an expression is evaluated, such as the std::string that city + ' Central' produces. It is destroyed at the end of the full expression that made it, unless a reference bound to it keeps it alive.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.