C++ Basics: Keep Range Search Results Attached to an Owner
A ranges search on a temporary vector returns a dangling marker instead of an iterator that would immediately outlive its storage.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need 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 ranges-dangling-temporary-result-demo.cpp:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <type_traits>
#include <vector>
int main()
{
using TemporaryResult = decltype(std::ranges::find(std::vector<int>{4, 8}, 8));
static_assert(std::is_same_v<TemporaryResult, std::ranges::dangling>);
std::cout << "temporary result: dangling marker\n";
const std::vector<int> values{4, 8};
const auto found = std::ranges::find(values, 8);
if (found != values.end()) {
std::cout << "owned result: " << *found << '\n';
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic ranges-dangling-temporary-result-demo.cpp -o ranges-dangling-temporary-result-demo &&
./ranges-dangling-temporary-result-demoObserved output:
temporary result: dangling marker
owned result: 8Read the result
The compile-time assertion verifies the temporary-vector result type without evaluating the expression. Naming the vector keeps storage alive so the successful iterator can be dereferenced.
Apply it carefully
The marker is a type, not a runtime lifetime monitor. A named owner can still be destroyed or reallocated while an iterator survives. Borrowed ranges such as span can return iterators even from temporary range objects, because destroying the view does not itself destroy its elements. You must still keep the underlying storage alive.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- ranges-dangling-temporary-result-demo.cpp ranges-dangling-temporary-result-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.