Learning Hub Search Ctrl K

Modern C++ › C++17

std::string_view

Non-owning string references and their lifetime risks.

Since C++17 intermediate #string_view#non-owning#strings#lifetime#performance

Explanation

std::string_view (header <string_view>) is a non-owning view of a contiguous character sequence: just a pointer and a length (16 bytes on 64-bit platforms). It can refer to a std::string, a string literal, a char array or any slice of them, without copying or allocating.

It is the best parameter type for read-only string arguments: one function accepts std::string, const char* and literals with no temporary std::string.

API: size(), empty(), data(), operator[], substr() (O(1), no copy!), find..., compare, remove_prefix(), remove_suffix(). It is not null-terminated, and has no c_str().

Example

#include <iostream>
#include <string>
#include <string_view>
#include <vector>

// accepts std::string, const char*, literals, substrings: no copies
bool startsWith(std::string_view s, std::string_view prefix) {
    return s.substr(0, prefix.size()) == prefix;
}

std::vector<std::string_view> split(std::string_view s, char sep) {
    std::vector<std::string_view> out;
    while (true) {
        auto pos = s.find(sep);
        out.push_back(s.substr(0, pos));
        if (pos == std::string_view::npos) break;
        s.remove_prefix(pos + 1);
    }
    return out;
}

int main() {
    std::string text = "name=Ann;age=30;city=Oslo";
    std::cout << startsWith(text, "name") << startsWith("hello", "help") << "\n";   // 10

    for (std::string_view part : split(text, ';'))             // views into 'text', no allocations
        std::cout << "[" << part << "]";
    std::cout << "\n";

    std::string_view sv = "constant text";                     // refers to the literal
    std::cout << sv.size() << " " << sv.substr(9) << "\n";     // 13 text

    // DANGER: the view outlives its data
    std::string_view bad;
    {
        std::string temp = "short-lived string that is long enough to be heap allocated";
        bad = temp;
    }
    // std::cout << bad;                                       // undefined behavior: temp is gone
    (void)bad;
    return 0;
}

Common pitfalls

  • Dangling views: a string_view never keeps its data alive. Don’t return one pointing at a local std::string, and don’t store one from a temporary (std::string_view v = std::string("x");).
  • Passing a view to a C API that expects a null-terminated string is wrong: data() is not guaranteed to end with '\0'. Copy into a std::string first.
  • No implicit conversion to std::string (it is explicit): write std::string(sv).
  • Don’t use it as a member unless you control the lifetime of the viewed data.
  • Comparing views compares contents, not addresses (unlike const char*).

Legacy vs modern

// C++98: pick one, or pay for a copy
bool startsWith(const std::string& s, const std::string& p);   // "x" creates a temporary string
bool startsWith(const char* s, const char* p);                  // loses size, needs strlen
// C++17: one signature for all
bool startsWith(std::string_view s, std::string_view p);

C++20 adds starts_with/ends_with and std::span<T>, the same idea for any contiguous array.

Exercises

1. Why is std::string_view f() { std::string s = "x"; return s; } a bug?

The returned view points into s, which is destroyed when f returns, so the caller receives a dangling view.