Skip to content

Borrow Text with string_view

The Course
•
40 min study

The tracker's parser receives a line like 2|25|todo|Read chapter and has to look at four pieces of it. With std::string::substr, each piece is a brand-new string with its own allocation, created only to be compared and thrown away. The parser does not need to own any of those pieces; it only needs to look at characters that already exist in the line.

std::string_view from <string_view> is a borrowed look at text. Internally it is just a pointer to the first character and a length, so creating one, copying one or taking a substr of one never allocates or copies characters. A function taking a std::string_view accepts a std::string, a string literal or part of either. The price is the one every borrow has: the view does not keep the characters alive. Whoever owns them must outlive every use of the view.

Predict and run

view borrows owner, and substr produces a second view into the same characters. What is printed?

Predict before running C++
#include <iostream>
#include <string>
#include <string_view>

int main() {
    std::string owner = "Read|25";
    std::string_view view = owner;
    auto separator = view.find('|');
    if (separator != std::string_view::npos) { std::cout << view.substr(0,separator) << "\n"; }
    return 0;
}
Check your prediction
Text
Read

find returns the index of |, here 4, or npos when there is none. The check matters: npos is the largest possible size, so substr(0, npos) would quietly mean "everything", and npos + 1, which a parser might use for the next field, wraps around to 0. Both are valid arithmetic that gives the wrong field. view.substr(0, 4) printed "Read" without creating a new string.

How views dangle

A view becomes dangling when the characters it points at are destroyed or moved. Reading a dangling view is undefined behavior. Three patterns cause almost all of it:

C++
std::string_view first_field(const std::string& line) {
    std::string copy = line;
    std::string_view view = copy;
    return view.substr(0, view.find('|')); // copy is destroyed on return.
}

std::string_view title = std::string("Read") + " chapter"; // The temporary dies at the semicolon.

std::string owner = "Read";
std::string_view borrowed = owner;
owner += " the whole chapter, slowly"; // May reallocate: borrowed now dangles.

The compiler catches some of these. Clang warns about the second one by default, so the browser editor shows the warning, but it is only a warning there: the program still runs and reads freed memory. A build with -Werror, like Day 7's local build, rejects it:

Shell
main.cpp:10:30: error: object backing the pointer will be destroyed at the end of the full-expression [-Werror,-Wdangling-gsl]
   10 |     std::string_view title = std::string("Read") + " chapter";
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It says nothing about the first or third. The returned view in first_field may even print the right text in a quick test, because the freed memory has not been reused yet. That is why the rules have to be habits rather than something you rely on the compiler for:

  • Use a view as a parameter, for reading during the call.
  • Return a std::string when the result must outlive the input.
  • Store std::string members, never views, unless the class clearly documents what it borrows from.
  • Do not change the owner while a view of it is in use.

Views are not C strings

A std::string always keeps a terminating null character after its contents. A view of part of a string does not: view.substr(0, 4).data() points at "Read|25" and nothing marks the end after "Read". Passing data() to a function that expects a null-terminated C string reads past the view. When you need an owning or null-terminated string, build one explicitly with std::string(view).

Views make field splitting cheap. Here each field is a view into line, and remove_prefix advances the view itself:

Walk the fields without copying C++
#include <iostream>
#include <string>
#include <string_view>

int main() {
    const std::string line = "2|25|todo|Read chapter";
    std::string_view rest = line;
    int index = 0;
    while (true) {
        const auto bar = rest.find('|');
        const std::string_view field = rest.substr(0, bar);
        std::cout << index++ << ": [" << field << "] " << field.size() << " chars\n";
        if (bar == std::string_view::npos) { break; }
        rest.remove_prefix(bar + 1);
    }
    return 0;
}
Text
0: [2] 1 chars
1: [25] 2 chars
2: [todo] 4 chars
3: [Read chapter] 12 chars

The loop is safe because line is const and outlives every view, and the loop finishes before anything could change it. The project's parse_task works on views the same way, and then builds an owning std::string for the title before returning a task.

Practice

Exercise

Your turn

Write std::vector<std::string_view> split(std::string_view line) that returns the |-separated fields, keeping empty ones, and std::vector<std::string> own(const std::vector<std::string_view>& fields) that copies them into owning strings. Create the source line 1||done|Plan inside an inner block, split and own it there, and print the owned fields after the block ends:

Text
fields: 4
[1]
[]
[done]
[Plan]
Your workspace C++
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

// Write split and own here.

int main() {
    std::vector<std::string> kept;
    {
        std::string source = "1||done|Plan";
        // Split, own, and store the result in kept.
    }
    // source is gone: print kept here.
    return 0;
}
Hint 1: the idea

The views are only valid inside the block, because they borrow from source. Copy into owning strings before the owner's lifetime ends, and print only the copies afterward.

Hint 2: a first step

Loop as the lesson did: find('|'), push_back(rest.substr(0, bar)), then break on npos or remove_prefix(bar + 1). In own, result.emplace_back(field) constructs a std::string from each view.

Show one solution
Run the solution C++
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

std::vector<std::string_view> split(std::string_view line) {
    std::vector<std::string_view> fields;
    while (true) {
        const auto bar = line.find('|');
        fields.push_back(line.substr(0, bar));
        if (bar == std::string_view::npos) { return fields; }
        line.remove_prefix(bar + 1);
    }
}

std::vector<std::string> own(const std::vector<std::string_view>& fields) {
    std::vector<std::string> result;
    for (std::string_view field : fields) { result.emplace_back(field); }
    return result;
}

int main() {
    std::vector<std::string> kept;
    {
        std::string source = "1||done|Plan";
        kept = own(split(source));
    }
    std::cout << "fields: " << kept.size() << "\n";
    for (const std::string& field : kept) { std::cout << "[" << field << "]\n"; }
    return 0;
}
Text
fields: 4
[1]
[]
[done]
[Plan]

The vector of views returned by split lives only until the end of the statement kept = own(split(source));, while source is still alive, so every view is read while valid. kept owns its characters, so printing it after the block is safe; printing the views there would be undefined behavior. The empty field between || shows the split keeps structure intact, which is what lets a parser reject a line for a missing value. The checkpoint applies the same owning-versus-borrowing choice to lookups in a map.

Was this article helpful?

Your response is saved on this device.