C++ Basics: Distinguish an Empty Suffix from an Invalid Offset
Use std::string::substr to copy a suffix, while recognizing that an offset equal to size is valid and an offset beyond size is not.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party 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-substr-end-boundary-demo.cpp:
#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
std::string name = "report";
std::cout << "clipped: " << name.substr(3, 100) << '\n';
std::cout << "at end size: " << name.substr(name.size()).size() << '\n';
try {
auto invalid = name.substr(name.size() + 1);
std::cout << invalid << '\n';
} catch (const std::out_of_range&) {
std::cout << "past end rejected\n";
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-substr-end-boundary-demo.cpp -o string-substr-end-boundary-demo &&
./string-substr-end-boundary-demoObserved output:
clipped: ort
at end size: 0
past end rejectedRead the result
A large requested count is clipped to the remaining suffix, producing ort. Starting exactly at the end gives an empty string. The intentional past-end request throws and is caught without depending on platform-specific exception wording.
Apply it carefully
Check an external position against size before using it when out-of-range input is expected. substr returns an owning string copy here; a string_view slice can avoid copying but depends on the original storage remaining valid. Positions and counts in std::string measure char elements, not user-perceived characters in UTF-8 text. Never confuse a valid empty result with evidence that the offset was invalid.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- string-substr-end-boundary-demo.cpp string-substr-end-boundary-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.