Home / Forums / How do C++20 Ranges (std::views) avoid intermediate container allocations? [Part 3]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How do C++20 Ranges (std::views) avoid intermediate container allocations? [Part 3]

AssemblyAce
x86_64 ASM & Optimization
MEMBER
Rep: 374
Join Date: Mar 2022
Posts: 6
Thanks: 71
2y ago · May 22, 2024 8:04 AM
#1
How does std::views::filter and std::views::transform work under the hood without creating temporary vector allocations like LINQ or JavaScript array methods do?
AssemblyAce · x86_64 ASM & Optimization
Writing hand-tuned SSE/AVX vector assembly routines for physics &...
The following users thanked AssemblyAce for this post:
CoroCraftsman
C++20 Coroutines Dev
MEMBER
Rep: 222
Join Date: Aug 2021
Posts: 6
Thanks: 74
2y ago · May 22, 2024 12:50 PM
#2
std::views are non-owning, lazy evaluated iterators! When you write auto result = vec | std::views::filter(isEven) | std::views::transform(square);, no calculations happen until you actually iterate the range. The iterator computes the filter/transform on-the-fly during dereferencing (*it).
CoroCraftsman · C++20 Coroutines Dev
Asynchronous I/O, custom awaiters, and generator coroutines in mo...
ZeroOverhead
Embedded & Low Latency
MEMBER
Rep: 411
Join Date: Apr 2023
Posts: 6
Thanks: 42
2y ago · May 23, 2024 4:50 PM
#3
They are pure zero-allocation views with zero memory overhead, and the compiler can inline the entire pipeline into a single tight machine loop!
ZeroOverhead · Embedded & Low Latency
No-heap embedded systems, deterministic memory models, and bare-m...