Skip to content

Lesson 4 of 9 · 27m

References, string_view, span, and the Dangling Boundary

Choose owning and non-owning parameter types deliberately, recognize when views dangle, and keep lifetime rules visible at API boundaries.

Modern C++ gave us excellent lightweight views: std::string_view in C++17 and std::span in C++20. It did not give us lifetime checking. Every year I see the same production bug dressed in new syntax: a function returns or stores a view of a temporary, the memory is reused, and the program prints plausible garbage until it doesn't. Views are powerful precisely because they do not own. That means you own the lifetime proof.

Match the parameter type to the need

void log_message(std::string_view message);       // reads characters, no ownership
void store_message(std::string message);          // takes or copies ownership
void mutate_buffer(std::span<std::byte> output);  // mutable contiguous view
Document& document();                             // non-null borrowed object

std::string_view is ideal for read-only text parameters when the caller's string outlives the call. It avoids allocation and works for literals, std::string, substrings, and contiguous buffers. It is not a string replacement. It is a window.

The canonical dangling bug

std::string_view label_for(const Config& cfg) {
    return std::string("env=") + cfg.environment;  // view of temporary
}

The temporary std::string dies at the end of the full expression. The returned view points at freed memory. Compilers sometimes warn, but they cannot reliably prove lifetimes through real programs. The fix is either return an owning std::string or make clear that the view refers to memory owned by the input:

std::string label_for(const Config& cfg) {
    return std::string("env=") + cfg.environment;
}

Never store a view unless the ownership chain is obvious

A view member makes the containing object only as valid as the memory behind the view:

struct Row {
    std::string_view name;   // dangerous unless owner outlives Row
};

Sometimes this is right: parser tokens pointing into an immutable input buffer that outlives all tokens. Often it is accidental. If an object escapes the current scope, crosses an asynchronous boundary, or enters a container, prefer owning data unless profiling and lifetime design justify otherwise.

string_view is not necessarily null-terminated

This is a brutal boundary bug with C APIs:

void write_syslog(std::string_view msg) {
    syslog(LOG_INFO, "%s", msg.data());  // wrong unless null-terminated
}

data() is not promised to end in `

syslog(LOG_INFO, "%.*s", static_cast<int>(msg.size()), msg.data());

std::span has the same truth in binary form: it knows pointer and size, not ownership.

Const references extend some temporaries — until they don't

Binding a temporary to a const reference parameter is fine for the duration of the call. Storing that reference is not. Returning it is worse. Lifetime extension rules are narrower than most programmers remember, and they do not make architectural lifetime decisions for you.

Field notes

  • Treat string_view as non-null-terminated unless you constructed it from a guaranteed terminated buffer and know the size convention.
  • std::span does not bounds-check operator[]; .at-style safety is not part of the abstraction.
  • A view of std::vector data can dangle after the vector reallocates, not only after it is destroyed.
  • If a function accepts a view and launches asynchronous work, either copy the data or prove the owner outlives completion — write that proof in the API contract.

Was this lesson helpful?

Sign in to rate