skip to content

What rule would you set for std::string_view in a C++ codebase's function parameters, return types and data members, and why?

level: principalimportance: should knowfreq 40%

answer

  1. parameters borrow for one call
  2. returns and members outlive it
  3. sinks take std::string by value
  4. documented views of *this
  5. warnings, lifetimebound, sanitizers

basics

~20 s

Take std::string_view for read-only parameters; return and store std::string by default. A parameter view is safe because the argument outlives the call; a returned or stored view is not. Allow documented views of *this, static data and short-lived parse results.

solid answer

~50 s

A practical team rule: **parameters yes, returns and members no, with named exceptions**. Read-only text parameters take `std::string_view` by value, because the argument outlives the call, provided the function does not itself modify the string the view came from. A function that keeps the text takes `std::string` by value and moves it in; one that must reach a C API takes `const std::string&` or `const char*`. Return `std::string` by default; return a view only from an accessor that views `*this`'s own member or static storage, document "valid until the object changes", and mark it with `[[clang::lifetimebound]]` where Clang is used. Store `std::string` in long-lived types; allow view members only in short-lived view types, such as a header parser's result, whose lifetime is nested in the buffer's. Avoid offering both `const std::string&` and `std::string_view` overloads, which makes a call with a literal ambiguous. Enforce with clang's dangling warnings and AddressSanitizer in CI.

code

cpp · 22 lines
cpp
#include <iostream>
#include <string>
#include <string_view>

class Request {
public:
    explicit Request(std::string raw) : raw_(std::move(raw)) {}
    // Returns a view into *this: valid until this Request is modified or destroyed.
    std::string_view method() const [[clang::lifetimebound]] { return std::string_view(raw_).substr(0, raw_.find(' ')); }
private:
    std::string raw_;
};

Request read_request() { return Request("GET /index.html HTTP/1.1"); }

int main() {
    Request r = read_request();
    std::string_view ok = r.method();                  // r outlives the view
    std::string_view bad = read_request().method();    // warns: the Request dies at ';'
    (void)bad;                                         // never read through bad
    std::cout << ok << '\n';
}

go deeper

for a junior

Use std::string_view for parameters you only read, and return std::string unless told otherwise.

for a middle

Explain why a view parameter is safe for the duration of the call while a view return or member depends on an unseen owner.

for a senior

Write sink, reader and C-boundary signatures correctly, and know which dangling shapes clang warns about and which it misses.

for a principal

Own the codebase rule and its exceptions, plan the migration bottom-up without ambiguous overloads, and back it with warnings, annotations and sanitizer runs.

## Why the position of the view decides its safety A `std::string_view` is safe exactly as long as the characters it points at stay alive and unchanged. Where the view appears in an API decides who has to guarantee that: - **As a parameter**, the caller's argument lives at least until the call returns; even a temporary lives until the end of the full-expression that contains the call. Inside the function, the view is safe by construction, as long as the function neither stores it nor modifies, through another name, the string it views (for example appending to a member that the caller passed in as a view). - **As a return type**, the view leaves the function, and its validity now depends on something the caller cannot see from the signature. - **As a data member**, the view lives as long as the object, which is usually much longer than the buffer it was sliced from. ## A default rule | position | default | exception | |---|---|---| | read-only parameter | `std::string_view` by value | `const std::string&` or `const char*` when the implementation must call a C API needing a terminator | | parameter the function keeps | `std::string` by value, then `std::move` into the member | none | | return value | `std::string` | a view of `*this`'s member or of static storage, documented and annotated | | data member | `std::string` | short-lived view types, such as a parsed request, nested inside the buffer's lifetime | | container element or map key | `std::string` | the same short-lived view types | The rule trades a few copies for the elimination of a whole class of use-after-free bugs, and keeps the zero-copy benefit where it is safe: on the way in. ## What the compiler catches and what it misses Clang has several warnings for the common shapes: - `-Wreturn-stack-address` for returning a view of a local `std::string`; - `-Wdangling-gsl` for initializing a view from a temporary `std::string`; - `-Wdangling` for a view taken from a temporary object through an accessor annotated `[[clang::lifetimebound]]`. They miss the cases that matter most for members. A constructor `Route(std::string_view p) : path(p) {}` called with `Route(prefix + "/players")` compiled without any warning on this machine, until the parameter was annotated with `[[clang::lifetimebound]]`. The rule exists because the compiler's coverage has holes; AddressSanitizer in CI covers more of them at run time, but not views into inline small strings. ## Costs to plan for when adopting views 1. **Ambiguous overload sets.** Keeping `log_line(const std::string&)` and adding `log_line(std::string_view)` makes `log_line("GET /index.html")` fail with `call to 'log_line' is ambiguous`, since a literal converts to both. Replace the old overload rather than adding beside it. 2. **Explicit conversions downstream.** A view converts to `std::string` only explicitly. If a function now takes a view but calls deeper functions that take `const std::string&`, each call needs `std::string(sv)`: a copy that did not exist before. Migrate from the leaves of the call graph upward. 3. **The lost terminator.** Functions that forward text to C APIs lose the guarantee a `const std::string&` gave them; keep those on string parameters. 4. **`auto` changes meaning.** `auto x = s.substr(...)` is an owning copy for a string and a borrowing view for a view, so changing a variable's type silently changes lifetimes in code that never mentions views. ## Where a lead bends the rule - **Parsers and tokenizers.** A `HeaderView { std::string_view name, value; }` produced and consumed inside one request's scope is the reason the type exists. Name such types as views, keep them out of long-lived containers and caches, and copy into `std::string` at the boundary where data leaves the request. - **Hot paths with measured copies.** Returning a view from an accessor, such as `std::string_view method() const`, is reasonable when profiling shows the copies matter and the accessor documents its lifetime. - **Static tables.** A `constexpr std::string_view` table of names refers to literals with static storage duration and never dangles. ## Enforcing it - Turn on Clang's dangling warnings as errors where the toolchain supports them. - Annotate view-returning accessors with `[[clang::lifetimebound]]` when building with Clang. - Run tests under AddressSanitizer in CI. - Make a returned or stored `std::string_view` a review checkpoint: what owns the characters, and what guarantees that owner outlives this view?

  • When is a std::string_view data member acceptable?
    When the object holding it is a view type by design and its lifetime is nested inside the owner's: a parser result created from a request buffer and discarded before that buffer is freed or grown. Name the type as a view, keep it out of caches and long-lived containers, and copy into `std::string` wherever the data must outlive the buffer.
  • Why should a sink parameter be std::string by value rather than std::string_view?
    A sink keeps the text, so it must end up in an owning `std::string`. With a view parameter the function always copies, even when the caller had a temporary it could have given away. With `std::string` by value, an rvalue argument is moved in and an lvalue is copied once, and the function then moves the parameter into its member.

  • Returning std::string_view is always faster and therefore always better.
  • Storing a std::string_view member is safe if it was built from a std::string.
  • Clang warns about every dangling string_view, so no rule is needed.
  • Add a string_view overload next to the const std::string& one for speed.
  • A sink function should take std::string_view and copy it inside.