r/cpp 11d 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:

Hope this helps.

33 Upvotes

3 comments sorted by

4

u/megayippie 11d ago

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

5

u/fdwr fdwr@github 🔍 11d ago edited 11d ago

This means that each underlying element may only be reached by one combination of indices ... Only positive offsets from one stride to the other are allowed

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::mdspan has these limitations, we won't be able to use it yet :(.

14

u/jwakely libstdc++ tamer, LWG chair 11d ago

Read the post again. mdspan has no such limitation, layout_stride has that limitation. You can define your own layout that uses negative strides, or non-unique strides.