C++ Basics: Keep std::string_view Within Its Owner Lifetime
std::string_view refers to characters it does not own. Borrow a slice while its source is alive, and make an owning string when data must survive the source scope.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install G++ and its C++ standard-library development files, and make g++ available on PATH. You also need Bash, a text editor, and mktemp, rm, and rmdir. No third-party C++ library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as string-view-owner-lifetime-demo.cpp:
#include <iostream>
#include <string>
#include <string_view>
int main()
{
std::string saved_prefix;
{
std::string record = "alpha:ready";
const std::string_view whole_record{record};
const auto separator = whole_record.find(':');
if (separator == std::string_view::npos) {
return 1;
}
const auto prefix = whole_record.substr(0, separator);
saved_prefix = std::string{prefix};
record[0] = 'A';
std::cout << "Borrowed: " << prefix << '\n';
std::cout << "Copied: " << saved_prefix << '\n';
}
std::cout << "After owner scope: " << saved_prefix << '\n';
}Compile and run it. The second command runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-view-owner-lifetime-demo.cpp -o string-view-owner-lifetime-demo &&
./string-view-owner-lifetime-demoObserved output:
Borrowed: Alpha
Copied: alpha
After owner scope: alphaRead the result
The prefix view refers to the first five characters of record. Changing an existing character changes what the view prints. saved_prefix owns a separate copy, so it remains lowercase and is still valid after record is destroyed. No view is used after the inner scope ends.
Apply it carefully
A view does not extend its owner lifetime. Returning a view of a local string or retaining a view after owner reallocation can leave a dangling reference. This example changes one existing character only; it does not resize or otherwise reallocate record. A view can also end before a null terminator, so do not pass its data pointer to an interface that requires a complete null-terminated string without an appropriate length or owning conversion.
The C++ working draft specifies the relevant library behavior. The example uses interfaces available in C++20; the current working draft also describes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- string-view-owner-lifetime-demo.cpp string-view-owner-lifetime-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.