liveBook · Manning

Std::string_view

As explained in Learn C++ by Example

std::string_view is a non-owning C++ standard library view over a contiguous sequence of characters.

std::string_view is a C++17 standard-library view that provides read-only access to an existing contiguous character sequence without copying it. Include <string_view> when using it. section 7.1.3

A view does not own its characters, so the original string must remain in scope while the view is used. Letting that string disappear makes the view invalid. section 7.1.3

Avoiding a substring copy

In the answer smash game, word.substr(0, offset) creates a temporary string before concatenation. std::format("{}{}", std::string_view(word).substr(0, offset), second_word) views the prefix instead, avoiding that substring copy.

How Learn C++ by Example covers it

How deep it goes
Defines read-only viewing and lifetime safety, then demonstrates prefix viewing without exploring implementation internals.
Examples
Demonstrates a prefix view while building an answer in a small answer smash game.
What it assumes
Assumes familiarity with std::string and substrings while teaching non-ownership and lifetime constraints explicitly.
What you can do after
Apply it via the standard library to pass or format existing character sequences without unnecessary copies.
How it connects
Connects std::string_view with std::string, substrings, std::format, temporary objects, and object lifetime.

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.