Codectionary / Developer documentation / C++

C++ std::string_view lifetimes

C++17 string_view represents a read-only slice of existing character storage. substr creates another view without allocating a string, making it useful for parsing data whose owner remains alive.

Syntax

std::string_view slice = text.substr(offset, count);

Examples

C++ std::string_view lifetimes

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <string>
#include <string_view>
#include <iostream>
int main() {
    std::string line = "status=ready";
    std::string_view view = line;
    auto value = view.substr(view.find('=') + 1);
    std::cout << value << '\n';
}
  1. Output: ready. line owns the bytes until main ends; value refers to five of those bytes.

Best practices

  • Never return a view into a local string or keep one after its owner changes storage. A view is not guaranteed to be null-terminated.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading