C++ › Ranges & Views

How does lazy evaluation in views affect performance and behavior?

Advanced

Answer

Views compute elements only when iterated and don't store results, so composing many views avoids intermediate allocations and can short-circuit (e.g., with take). But re-iterating recomputes, side-effecting transforms run per traversal, and some views are single-pass. Understanding laziness is key to correct and efficient range pipelines; materialize with std::ranges::to (C++23) when you need a container.
auto v2 = pipeline | std::ranges::to<std::vector>(); // materialize (C++23)
Real-world example A lazy pipeline avoids building temporaries, but the team materializes the result once for repeated use.

Common follow-ups: Why can re-iterating recompute? | How do you materialize a view?