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';
}- 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