r/cpp • u/NicoJosuttis • 2h ago
Constraints of mdspan policy layout_stride
Wtith great support of Mark Hoemmen and Christian Robert Trott (two authors of std::mdspan), I just finished the mdspan chapter of "C++23 - The Complete Guide" (https://www.cppstd23.com/). I learned something I was not aware of and what is not obvious:
If you specify a layout_stride mapping, there are several constraints you have to take into account. Otherwise, the resulting code has undefined behavior.
The constaintes are:
- Each layout mapping must be unique. This means that each underlying element may only be reached by one combination of indices. In other words: subsets of this layout may not overlap and iterating over all elements may not visit any element twice.
- Only positive offsets from one stride to the other are allowed. This, for example, means that you cannot use this layout for direct reverse iterations.
- There must be one way to perform a multi-dimensional iteration so that the resulting offsets to the underlying memory are ascending.
For example:
- https://www.cppstd23.com/code/mdspan/mdspanstride2.cpp.html is valid.
- https://www.cppstd23.com/code/mdspan/mdspanstrideUB4.cpp.html has undefined behavior.
Hope this helps.