September 12, 2026

std::string_view Removed the Copy. It Did Not Give You Ownership

std::string_view can remove a string copy. It does not remove the lifetime problem. In many APIs, it quietly moves that problem somewhere else.

Consider this setter:

class Device
{
public:
    void setName(std::string_view name)
    {
        name_ = name;
    }

private:
    std::string_view name_;
};

It looks efficient. There is no allocation and no character copy. The parameter accepts a std::string, a string literal, or another view.

Then someone writes:

device.setName(getDeviceName());

If getDeviceName() returns a std::string, the temporary string remains alive until the end of that full expression. The call to setName() itself is fine.

Then the semicolon is reached. The temporary string is destroyed. Device::name_ still contains an address and a length, but the characters it refers to no longer belong to a live object.

The optimization worked. The copy disappeared.

So did the ownership.

Context

In Stop Passing Everything by const&, I recommended std::string_view for APIs that only need to observe text during a call. This article covers the other half of that recommendation: what happens when the view escapes, is returned, stored, queued, or survives a mutation of its backing storage.

1 string viewdidnotgiveyouownership

The useful mental model: a view is a borrow


std::string_view does not contain a string in the ownership sense. Conceptually, it contains enough information to describe a contiguous sequence of characters:

  • a pointer to the first character;
  • a number of characters.

Copying the view copies that description. It does not copy the characters.

std::string text = "device-ready";

std::string_view first = text;
std::string_view second = first;

first and second both refer to characters owned by text. Neither view keeps text alive.

That is why std::string_view is so useful for function parameters. If the function only needs to inspect text while the call is active, ownership is unnecessary.

bool isSystemService(std::string_view name)
{
    return name.ends_with(".service");
}

std::string name = readUnitName();

isSystemService(name);
isSystemService("network.service");

Both calls are natural. No extra std::string is required just to give the function a sequence of characters.

The lifetime question appears when the function stops being an observer and lets the view escape.

Useful mental model

Read std::string_view as borrow these characters, not here is a cheap string.

A temporary is not automatically a problem


One source of confusion is that passing a temporary string to a function taking std::string_view can be perfectly safe.

void logDevice(std::string_view name)
{
    std::cout << "device=" << name << '\n';
}

logDevice(getDeviceName());

Assuming getDeviceName() returns a std::string, the temporary string remains alive while logDevice() is executing. The view is used before the temporary is destroyed.

The problem begins when the view survives longer than the expression that owns its characters:

std::string_view name = getDeviceName();

// getDeviceName()'s temporary std::string is already gone here.

process(name); // dangling view

The same problem exists in the original setter:

device.setName(getDeviceName());

// Device::name_ now refers to the destroyed temporary.

This distinction matters during code review. The suspicious part is not simply “temporary converted to string_view”. The real question is:

Can the view outlive the storage that produced it?

2 string viewdidnotgiveyouownership

string_view does not extend a temporary’s lifetime


This is especially easy to get wrong if you are used to lifetime extension through references.

const std::string& name = getDeviceName();

// The temporary bound directly to this local const reference
// has its lifetime extended.

use(name);

Replacing the reference with a view changes the contract:

std::string_view name = getDeviceName();

// No lifetime extension.
// The temporary string has already been destroyed.

use(name);

std::string_view is a separate object containing a borrow. It is not a reference that extends the lifetime of the object used to initialize it.

Common mistake

Do not assume that replacing const std::string& with std::string_view preserves every lifetime property of the original API. It may preserve how the text is read while changing how long the underlying storage is guaranteed to exist.

API input and stored state are two different contracts


This is the design distinction I find most useful in production code.

If the function only needs the text during the call, a view is often a very good parameter:

bool validateDeviceName(std::string_view name)
{
    return !name.empty() &&
           name.size() <= 64 &&
           name.find('/') == std::string_view::npos;
}

The function observes characters. It does not keep them.

A setter has a different job. If Device must keep the name independently of the caller, the member should normally own the characters:

class Device
{
public:
    void setName(std::string name)
    {
        name_ = std::move(name);
    }

private:
    std::string name_;
};

Now the ownership contract matches the object lifetime. Passing a temporary works naturally:

device.setName(getDeviceName());

The temporary can be moved into the parameter and then into the member.

There is another valid design. The setter can accept a std::string_view but explicitly copy its characters into an owning member:

class Device
{
public:
    void setName(std::string_view name)
    {
        name_.assign(name);
    }

private:
    std::string name_;
};

This is also safe. The parameter is borrowed input; the member is owned state.

The two setter designs have different performance characteristics. A value parameter can efficiently consume an rvalue std::string. A view parameter followed by assign() always copies the characters, but can be convenient when the API accepts many text sources and may allow the existing member allocation to be reused.

The dangerous version is not “a setter accepts string_view”. The dangerous version is “an object that needs independent state stores a borrowed view without a lifetime plan”.

3 string viewdidnotgiveyouownership

Storing a string_view can be correct — but the lifetime must be architectural


There are valid reasons to keep a std::string_view in an object.

A parser may keep views into an immutable message buffer. A configuration view may refer to a memory-mapped file. A table may contain views into string literals with static storage duration. A protocol decoder may expose fields without allocating a new string for every field.

For example:

struct HttpRequestView
{
    std::string_view method;
    std::string_view target;
    std::string_view host;
};

This can be a very efficient representation if every field points into one receive buffer that is guaranteed to remain alive and unchanged while the request view exists.

The architecture then needs to make that relationship real.

This is much weaker:

HttpRequestView parseRequest(std::string_view input);

auto request = parseRequest(readRequestFromSocket());

// What owns the bytes referenced by request now?

If readRequestFromSocket() returns an owning temporary string, the parsed fields may already be dangling after that statement.

A safer call site keeps the owner visible:

std::string buffer = readRequestFromSocket();

HttpRequestView request = parseRequest(buffer);

// request is valid while buffer remains alive and its storage
// is not invalidated.

Production recommendation

If an object contains non-owning views, make that visible in its name and architecture. Names such as MessageView, ParsedFrameView or ConfigView are useful because they tell reviewers to look for the owner.

Returning string_view creates a lifetime relationship with the caller


A returned std::string_view can be perfectly valid. It can also be one of the easiest ways to return a dangling pointer.

This function is broken:

std::string_view buildDeviceName()
{
    std::string name = readVendor();
    name += '-';
    name += readModel();

    return name;
}

The returned view refers to a local std::string. The string is destroyed before the caller can use the view.

The return type should be owning:

std::string buildDeviceName()
{
    std::string name = readVendor();
    name += '-';
    name += readModel();

    return name;
}

Returning a subview of caller-owned input is different:

std::string_view stripPrefix(std::string_view value,
                             std::string_view prefix)
{
    if (value.starts_with(prefix)) {
        value.remove_prefix(prefix.size());
    }

    return value;
}

This function does not create storage. Its result borrows from the first argument.

With a named owner, that is easy to reason about:

std::string path = getDevicePath();

std::string_view relative =
    stripPrefix(path, "/sys/devices/");

use(relative); // path still owns the characters

But the same API permits this:

std::string_view relative =
    stripPrefix(getDevicePath(), "/sys/devices/");

// relative is dangling now.

The function itself did nothing wrong during the call. The danger comes from composing a borrowed return value with temporary input.

Code-review question

Whenever a function returns std::string_view, ask one question before reading its implementation: who owns the characters returned to the caller?

4 string viewdidnotgiveyouownership

Returning a view into a member is useful, but still borrowed


A common and reasonable API is:

class Device
{
public:
    std::string_view name() const noexcept
    {
        return name_;
    }

private:
    std::string name_;
};

The returned view points into storage owned by Device. It can be used while the object remains alive and while the relevant string storage remains valid.

This can still surprise a caller:

std::string_view oldName = device.name();

device.setName("a-much-longer-device-name-that-may-reallocate");

log(oldName); // potentially dangling

The problem is not limited to object destruction. Mutation of the owner can invalidate the borrowed storage too.

For public APIs, document this explicitly if callers are expected to keep the returned view. If keeping it is not useful, consider whether returning const std::string&, an owning value, or a narrower callback-style API better expresses the intended lifetime.

A live owner is not enough: its storage can move


A second class of bugs appears when the owner still exists but the memory containing its characters changes location.

Consider a receive buffer:

std::vector<char> buffer = readPacket();

std::string_view serial{
    buffer.data() + serialOffset,
    serialLength
};

appendNextChunk(buffer);

process(serial);

If appendNextChunk() grows the vector beyond its capacity, std::vector reallocates its storage. References and pointers into the old allocation are invalidated.

The std::string_view does not know that this happened. Its pointer is not automatically adjusted.

The same general rule applies to views into a std::string. Operations that mutate the string may invalidate pointers into its character storage. A view created before such an operation should not be assumed to remain usable unless the operation’s guarantees make that safe.

std::string message = readHeader();

std::string_view type = message.substr(0, 4);

message += readPayload(); // may invalidate type

dispatch(type);

There is another subtle failure mode: the address may remain valid while the bytes change underneath the view.

std::string state = "READY";

std::string_view current = state;

state[0] = 'N';

std::cout << current; // observes "NEADY"

No pointer has to dangle for a borrowed view to become semantically wrong. A view is an alias of somebody else’s characters.

5 string viewdidnotgiveyouownership

reserve() reduces reallocations. It does not create ownership.


A common reaction is to reserve enough storage before creating views:

std::vector<char> buffer;
buffer.reserve(4096);

readInto(buffer);

std::string_view header{
    buffer.data(),
    headerLength
};

This can be a useful implementation technique. As long as operations do not exceed the reserved capacity and do not otherwise invalidate the relevant elements, you avoid reallocation.

But reserve() is not an ownership model.

A later firmware feature may increase the maximum packet size. A new field may push the buffer past its expected capacity. Somebody may replace the container. Somebody may clear and refill it. The code can still compile while the lifetime assumption silently changes.

Warning

Do not use capacity planning as a substitute for documenting borrowed lifetime. Reserving storage is a performance and invalidation-management technique, not proof that a view owns anything.

Be very careful with containers of string_view


A container can make views look more permanent than they really are:

std::vector<std::string_view> fields;

The vector owns the string_view objects. It still does not own a single character referenced by those views.

This parser pattern can be efficient:

std::string line = readLine();

std::vector<std::string_view> fields =
    splitIntoViews(line);

But every element of fields depends on line.

If the code later reuses the buffer:

line = readLine();

process(fields);

the stored views may be dangling, may refer to different characters, or may appear to work depending on what happened to the string’s allocation.

The same caution applies to associative containers:

std::string name = "camera";

std::unordered_map<std::string_view, int> ids;
ids.emplace(name, 42);

name[0] = 'C';

The view stored as the key still points to the same characters, but those characters now spell something different. Hashing and equality observe the characters, so the key’s effective value has changed without the container relocating it to the bucket corresponding to that new value.

This is a nasty class of bug because there is no dangling pointer yet. The ownership and immutability contract is simply wrong.

Rule for associative containers

Use std::string_view as a stored key only when the backing character storage has a stable lifetime and effectively immutable contents for at least as long as the container needs the key.

Ring buffers create another kind of lifetime bug


Embedded and networking code often uses long-lived buffers specifically to avoid allocation. That removes one lifetime problem but can create another.

Imagine a receive buffer that remains allocated for the entire connection:

std::array<char, 4096> rxBuffer;

std::string_view readFrame()
{
    const std::size_t bytes =
        socket.read(rxBuffer.data(), rxBuffer.size());

    return {
        rxBuffer.data(),
        bytes
    };
}

The returned view does not immediately dangle. The array continues to exist.

But the next call to readFrame() overwrites the same storage.

std::string_view first = readFrame();
std::string_view second = readFrame();

process(first); // first may now observe bytes from the second frame

This is an important distinction:

  • A dangling view points at storage that is no longer valid.
  • A reused-buffer view may still point at valid memory, but the memory no longer contains the logical object the caller thought it borrowed.

Both are lifetime-design bugs from the caller’s perspective.

Async code turns borrowing into an ownership decision


This pattern deserves special attention because it looks safe at first glance:

void DeviceClient::scheduleLog(std::string_view message)
{
    scheduler_.post([message] {
        writeLog(message);
    });
}

The lambda captures message by value.

That sounds reassuring until we remember what is being copied. The lambda copies the std::string_view. It does not copy the characters.

This call can therefore be broken:

client.scheduleLog(buildDiagnosticMessage());

The temporary message can disappear long before the scheduler executes the callback.

If queued work must keep the message, make that ownership explicit:

void DeviceClient::scheduleLog(std::string_view message)
{
    scheduler_.post([
        message = std::string(message)
    ] {
        writeLog(message);
    });
}

Or make the ownership transfer visible in the function contract:

void DeviceClient::scheduleLog(std::string message)
{
    scheduler_.post([
        message = std::move(message)
    ] {
        writeLog(message);
    });
}

For asynchronous APIs, I generally prefer the second form when the operation logically owns the data until completion. It tells the caller that this is not a synchronous observation.

6 string viewdidnotgiveyouownership

string_view is not a C string


Lifetime is not the only contract difference between std::string and std::string_view.

A std::string provides a null terminator after its characters. A std::string_view only describes a sequence of characters with a length. The character immediately after the view is not required to be '\0'.

This means that the following conversion is not generally valid:

void openDevice(std::string_view path)
{
    const int fd = ::open(path.data(), O_RDONLY);
    // BUG: open() expects a null-terminated path.
}

It may appear to work when the view represents an entire std::string or a string literal. Then someone passes a subview:

std::string text = "/dev/ttyUSB0:115200";

std::string_view path{
    text.data(),
    std::string_view{"/dev/ttyUSB0"}.size()
};

openDevice(path);

The view contains only /dev/ttyUSB0, but path.data() points into a larger buffer. A C function scanning until '\0' can continue into :115200.

If the C API accepts an explicit length, pass both pieces:

writeBytes(view.data(), view.size());

If it requires a null-terminated string, create one at the boundary:

void openDevice(std::string_view path)
{
    const std::string ownedPath{path};

    const int fd =
        ::open(ownedPath.c_str(), O_RDONLY);

    // ...
}

Yes, that performs a copy. That copy may be exactly what the C API contract requires.

Warning

Do not pass string_view::data() to an API that accepts only const char* unless you independently know that a null terminator exists exactly where that API expects it.

7 string viewdidnotgiveyouownership

Embedded NUL characters are another reason to keep length visible


A view can also contain embedded zero characters:

const char bytes[] = {
    'A', 'B', '\0', 'C', 'D'
};

std::string_view value{
    bytes,
    sizeof(bytes)
};

From the view’s perspective, those are five characters. A traditional C-string API will usually interpret the first zero as the end of the string.

This matters in protocol parsers, binary metadata, IPC payloads and any interface where “text-like bytes” do not necessarily follow C-string rules.

Keeping pointer and length together is one of the reasons std::string_view is useful. Throwing away the length by immediately calling a C API with only data() loses part of that safety.

Views across subsystem boundaries deserve extra suspicion


Lifetime assumptions become harder to verify when a view crosses architectural boundaries.

Examples include:

  • a parser returning views into a networking buffer;
  • a D-Bus adapter passing views into asynchronous application logic;
  • a logging layer queuing views for another thread;
  • a worker queue storing views into request objects;
  • a cache keeping views into a configuration buffer that can be reloaded;
  • an automotive middleware layer keeping views into receive buffers owned by the transport stack.

The farther the view travels from its owner, the harder it becomes for a reviewer to prove that the relationship remains valid.

At module boundaries, asynchronous boundaries and public interfaces, an extra string copy can be cheaper than an invisible lifetime dependency.

Practical boundary rule

Use views freely inside a well-defined synchronous scope. Become increasingly conservative as a view crosses object, thread, queue, callback, module or subsystem boundaries.

Why these bugs survive testing


A dangling std::string_view does not clear itself when its owner disappears.

It still contains an address and a size.

Sometimes the old bytes are still sitting at that address when you inspect them. The first call works. The unit test passes. GDB prints exactly the string you expected.

Then another allocation reuses the memory and the bug appears somewhere completely unrelated.

Typical symptoms include:

  • corrupted text that appears only under load;
  • a device name changing after an unrelated operation;
  • failures appearing only with longer strings because short strings use a different internal storage strategy;
  • a parser working in debug builds but failing under optimization;
  • a callback logging valid text most of the time and garbage occasionally;
  • a C API reading characters past the logical end of the view.

This is why lifetime bugs should be treated as correctness defects even when the current test device appears stable.

Use sanitizers to make lifetime failures louder


AddressSanitizer is extremely useful when a dangling view eventually reads destroyed stack or heap storage.

For a development build with GCC or Clang, a useful starting point is:

-fsanitize=address,undefined -fno-omit-frame-pointer -g

Then deliberately exercise the dangerous call patterns:

device.setName(getDeviceName());

stressAllocator();

use(device.name());

Do not only test the convenient lvalue case:

std::string name = getDeviceName();
device.setName(name);

The temporary case is often the one that reveals whether the API accidentally stores borrowed storage.

Sanitizers are not a proof that every view is safe. A dangling pointer may still reference memory that has not yet been reused. Treat them as bug detectors, not lifetime verification.

Static analysis can find patterns humans miss


This is also a good area for compiler diagnostics and static analysis because many mistakes have recognizable shapes.

Useful Clang tooling includes checks for dangling handles and suspicious use of string_view::data(). Recent Clang lifetime analysis can also diagnose several cases where borrowed storage escapes its valid scope.

For clang-tidy, two checks worth enabling in a C++ codebase using views heavily are:

bugprone-dangling-handle
bugprone-suspicious-stringview-data-usage

These tools do not understand every architectural lifetime relationship, but they are useful because humans tend to focus on business logic during reviews and miss a two-line borrow that escapes into a member or container.

Debugging clue

If a corrupted string is represented by std::string_view, do not start by asking only “who wrote bad characters here?”. First identify the owner of the referenced bytes and reconstruct every operation that could destroy, move, resize, reuse or modify that storage.

A practical API decision table


The easiest way to use std::string_view safely is to decide first whether the API is borrowing or owning.

API requirementTypical choiceLifetime implication
Read text only during this function callstd::string_viewCaller only needs storage alive for the call
Store text independentlystd::stringCallee owns its state
Accept generic text input, then store a copystd::string_view parameter + std::string memberBorrow ends inside the call
Consume or store a caller-produced string efficientlystd::string by valueOwnership is transferred/copied into the call
Return part of caller-provided textstd::string_viewResult cannot outlive the caller’s backing storage
Return newly generated textstd::stringReturned value owns its characters
Store parsed fields referring to one immutable backing bufferView type such as MessageViewBacking buffer must outlive every view
Queue work for another thread or later callbackUsually owning std::stringQueued operation owns data until execution
Call C API requiring pointer + lengthdata() + size()No null-termination assumption needed
Call C API requiring a C stringOwning/null-terminated stringMaterialize a std::string unless termination is independently guaranteed

The table is not a language rule. It is a useful default for making lifetime decisions visible instead of accidental.

8 string viewdidnotgiveyouownership

Common string_view failure modes


These are the patterns I would specifically look for during code review:

  • View member initialized from an unconstrained parameter. Ask who guarantees that the caller’s storage outlives the object.
  • Temporary converted to a view that escapes the expression. The conversion is legal; the resulting lifetime is not necessarily useful.
  • Function returns a view into local or by-value state. The owner disappears before the caller uses the result.
  • Returned subview composed with a temporary argument. Each individual API looks reasonable, but the combination dangles.
  • View survives mutation of its backing std::string or buffer. Storage may move or characters may change underneath the view.
  • Views into a growing std::vector. Reallocation invalidates addresses into the old allocation.
  • Container of views with no obvious owner nearby. The container owns the views, not their data.
  • string_view used as a map or hash-map key over mutable storage. Changing the backing characters changes the effective key without updating the container structure.
  • View captured into asynchronous work. Capturing the view by value does not extend the lifetime of its characters.
  • view.data() passed to a null-terminated C API. The API may read past the logical end of the view.

Production recommendations


std::string_view is not dangerous by itself. Hidden lifetime relationships are dangerous.

  • Prefer views for synchronous observation. Parameters to parsers, validators, search helpers and formatting logic are usually good candidates.
  • Prefer ownership for persistent state. Members representing an object’s independent name, path, identifier or configuration should normally own their characters.
  • Do not optimize away a copy until you understand what that copy was buying you. Sometimes the copy is also the lifetime boundary.
  • Make view-like objects obvious. A type named PacketView communicates a different contract from a type named Packet.
  • Keep owners visually close to long-lived views. If proving the relationship requires following five objects across three modules, the design is already difficult to maintain.
  • Copy at asynchronous boundaries unless ownership is otherwise guaranteed. Queues, worker threads and callbacks routinely outlive caller-owned buffers.
  • Assume mutations deserve a lifetime review. When backing strings or buffers resize, reallocate, reload or are reused, revisit every outstanding view.
  • Keep length information when crossing C boundaries. Prefer pointer-and-length APIs. Materialize a null-terminated string when the target API requires one.
  • Run sanitizers and static analysis in CI. Lifetime bugs are exactly the kind of defect that can look correct until allocator behaviour changes.

The review question I would keep

Whenever a std::string_view is stored or returned, point at the characters it refers to and ask: which object owns these bytes, and what proves that object and its storage remain valid for the entire lifetime of this view?

The copy may have been part of the contract


std::string_view is one of the most useful small abstractions in modern C++. It lets APIs accept text without forcing allocation, copying or one specific owning string type.

But its efficiency comes directly from what it does not do.

It does not own the characters. It does not extend their lifetime. It does not follow them when their storage moves. It does not promise null termination. Copying a view does not copy the text. Capturing it into a callback does not keep the text alive.

For local synchronous code, those properties make std::string_view excellent.

For stored state, returned values, mutable backing buffers, queues, asynchronous work and C interfaces, they become part of the API contract.

The useful question is therefore not:

“Can I replace this std::string with std::string_view and remove a copy?”

It is:

“If I remove this copy, who owns the characters now?”