skip to content

Why does C++20 std::ranges::find(loadReadings(), 7, &Reading::sensorId) return std::ranges::dangling instead of an iterator, and when does it not?

level: seniorimportance: should knowfreq 35%

answer

  1. the argument is a temporary
  2. the iterator would outlive it
  3. borrowed_range is the exception
  4. lvalues are always borrowed
  5. string_view, span, iota qualify

basics

~20 s

The temporary vector from loadReadings() dies at the end of the statement, so an iterator into it would dangle. For an rvalue range that is not borrowed, ranges algorithms return std::ranges::dangling, which cannot be dereferenced.

solid answer

~40 s

Ranges algorithms that return an iterator or subrange into their argument use `std::ranges::borrowed_iterator_t<R>` as the return type. If `R` is an rvalue whose type does not model `std::ranges::borrowed_range`, that alias is `std::ranges::dangling`, an empty struct with no `operator*` or `operator->`. A temporary `std::vector` is destroyed at the end of the full-expression, so any iterator into it would dangle; returning `dangling` makes `it->celsius` a compile error rather than undefined behaviour. A range is **borrowed** when its iterators do not depend on the range object staying alive: every lvalue reference, and types that opt in through `std::ranges::enable_borrowed_range`, such as `std::string_view`, `std::span`, `std::ranges::subrange`, `views::iota` and `ref_view`. Fix it by storing the vector in a named variable first, or by returning a value rather than an iterator. Adaptors like `views::filter` are not borrowed.

code

cpp · 10 lines
cpp
#include <algorithm>
#include <vector>

struct Reading { int sensorId; double celsius; };
std::vector<Reading> loadReadings() { return {{1, 21.5}, {7, 98.0}}; }

int main() {
    auto it = std::ranges::find(loadReadings(), 7, &Reading::sensorId);
    return static_cast<int>(it->celsius);
}

go deeper

for a junior

Know that ranges algorithms on a temporary container give you something you cannot dereference, and that naming the container fixes it.

for a middle

Explain borrowed_iterator_t, why lvalues are always borrowed, and which standard types are borrowed even as rvalues.

for a senior

Diagnose dangling compile errors quickly, decide when a custom non-owning range may opt into enable_borrowed_range, and know what the check does not cover.

for a principal

Treat iterator-returning APIs on temporaries as a review smell and prefer value-returning helpers in shared code.

## The bug it prevents Before C++20, nothing stopped this: ```cpp auto it = std::find_if(loadReadings().begin(), loadReadings().end(), isSensor7); // two different temporaries ``` or, more subtly, a helper returning an iterator into a vector it received by value. An iterator into a destroyed container compiles fine and has undefined behaviour when used. The ranges library closes the most common form of this hole at compile time. ## How the return type changes Every `std::ranges` algorithm that returns a position inside its range argument declares the return type through `std::ranges::borrowed_iterator_t<R>` (or `borrowed_subrange_t<R>`). The rule, from the standard: - if `R` models `std::ranges::borrowed_range`, the alias is the ordinary `iterator_t<R>`; - otherwise it is `std::ranges::dangling`. `std::ranges::dangling` is an empty struct that can be constructed from anything and does nothing. It has no `operator*`, no `operator->`, no comparison with iterators. So: ```cpp auto it = std::ranges::find(loadReadings(), 7, &Reading::sensorId); // it is std::ranges::dangling it->celsius; // compile error ``` Apple clang 21 reports that the member reference type `borrowed_iterator_t<std::vector<Reading>>` (aka `std::ranges::dangling`) is not a pointer. The algorithm still runs - the search happens - but its result cannot be misused. ## What counts as borrowed `borrowed_range<T>` is defined as `range<T> && (is_lvalue_reference_v<T> || enable_borrowed_range<remove_cvref_t<T>>)`. In words: 1. **Any lvalue range is borrowed.** Passing `readings` (a named vector) gives a normal iterator, because the caller controls the vector's lifetime. 2. **Some types are borrowed even as rvalues**, because their iterators point into storage the range object does not own. The standard opts these in by specialising `std::ranges::enable_borrowed_range`: | Borrowed as rvalue | Not borrowed as rvalue | |---|---| | `std::string_view`, `std::span` | `std::vector`, `std::string`, `std::list` | | `std::ranges::subrange`, `std::ranges::ref_view` | `std::ranges::filter_view`, `transform_view` | | `views::iota`, `views::empty` | `std::ranges::owning_view` over a vector | | `take_view` and `drop_view` over a borrowed range | `take_view` over a non-borrowed range | So `std::ranges::find(std::string_view(buffer), ',')` returns a real iterator: it points into `buffer`, which outlives the temporary `string_view`. ## Making your own type borrowed A non-owning range type of your own - a handle into a ring buffer of telemetry, say - can opt in: ```cpp template<> inline constexpr bool std::ranges::enable_borrowed_range<SampleWindow> = true; ``` Do this only if iterators remain valid after the `SampleWindow` object is destroyed; lying here reintroduces exactly the dangling bug the mechanism prevents. ## Fixes when you meet dangling - **Name the container:** `auto batch = loadReadings(); auto it = std::ranges::find(batch, 7, &Reading::sensorId);`. - **Return a value, not a position:** `std::ranges::count_if`, `std::ranges::any_of` and `std::ranges::max` return values and never dangle. - **Keep the owner alive in the pipeline:** piping an rvalue container into a view adaptor creates an `owning_view` that holds it, so `loadReadings() | views::filter(isHot)` is safe to iterate - but algorithms that return iterators into such a temporary pipeline still yield `dangling`. ## Subranges and dangling Algorithms that return a range rather than one iterator use `std::ranges::borrowed_subrange_t<R>`. `std::ranges::equal_range`, `std::ranges::search` and `std::ranges::remove` follow the same rule: on a non-borrowed rvalue they return `std::ranges::dangling` instead of a `std::ranges::subrange`. Structured bindings make the effect visible early - `auto [first, last] = std::ranges::equal_range(loadSorted(), key);` does not compile, because `dangling` has nothing to bind. The opposite also holds. A `std::ranges::subrange` is itself borrowed, so slicing one out of a named container and passing it on as a temporary is safe for the algorithms - the lifetime question has moved to whoever owns the container, which is exactly where it belongs. ## Limits The check covers only the algorithm's own return value. It does not catch a view stored past its source's lifetime, a `string_view` field outliving its buffer, or an iterator saved from a named container that is later destroyed. Those remain lifetime bugs for review, sanitizers and the material on dangling references.

  • Why does std::ranges::find(std::string_view(buffer), ',') return a usable iterator even though the string_view is a temporary?
    `std::string_view` specialises `std::ranges::enable_borrowed_range` to true: its iterators point into the characters it views, not into the `string_view` object. When the temporary view dies, the characters in `buffer` remain, so the iterator is still valid as long as `buffer` is. The algorithm therefore returns a normal iterator, not `std::ranges::dangling`.
  • Is loadReadings() | std::views::filter(isHot) safe to iterate in a range-for loop?
    Yes in a conforming C++20 library: piping an rvalue container into an adaptor wraps it in `std::ranges::owning_view`, which moves the vector into the view, so the data lives as long as the pipeline. The temporary pipeline is then kept alive by the range-for's reference. What stays unsafe is storing an iterator from an algorithm called on that temporary pipeline; it is not borrowed, so the algorithm returns `dangling`.

  • Saying std::ranges::dangling means the algorithm found nothing
  • Believing every ranges algorithm on a temporary fails to compile
  • Specialising enable_borrowed_range for a type that owns its elements
  • Assuming the dangling check catches views stored past their source
  • Calling a named std::vector argument non-borrowed

Assumes C++23; std::ranges::dangling, borrowed_range and enable_borrowed_range are C++20, and owning_view arrived as a defect report against C++20.