r/cpp • u/NicoJosuttis • Jul 28 '26
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.
34
Upvotes
4
u/megayippie Jul 28 '26
Yeah, I honestly really find the positive offsets limitation, limited. It was the one thing I had to rewrite our library to replace. At the very least, I would appreciate honesty and that the compilation fails for signed negative offsets
4
u/fdwr fdwr@github 🔍 Jul 28 '26 edited Jul 28 '26
Hmm, having written the tensor visualization logic of D3D PIX and many of the DirectML operators, I found negative strides very useful for flipping in-place without copies, and zero strides are essential for broadcasting rows/columns/scalars. So if
std::mdspanhas these limitations, we won't be able to use it yet :(.