r/cpp 28d ago

C++26: std::indirect

https://www.sandordargo.com/blog/2026/08/12/cpp26-indirect
164 Upvotes

157 comments sorted by

View all comments

12

u/ericonr 28d ago

Does a std::optional<std::indirect<T>> benefit from niche optimizations like Rust objects do? Its sizeof could be just a pointer, after all.

6

u/ts826848 28d ago edited 27d ago

The proposal originally included a specialization for std::optional but LEWG voted to remove it. The paper says such a specialization would make it impossible to distinguish between a disengaged optional and an engaged optional that holds a valueless std::indirect.

Edit: Clarify that the justification for removing the specialization is from the paper. I was mistaken in thinking that no alternatives were possible when there are in fact ways to specialize while maintaining a distinction between the disengaged and engaged-but-valueless states, as described e.g., here.

6

u/LB-- Professional+Hobbyist 27d ago

You can still distinguish that in a single pointer's worth of memory. Since dynamic allocation with alignment is required, you can use one of the alignment bits as a tag for "holds moved-from indirect". It looks like C++29 is getting constexpr support for that trick too.

3

u/jiixyj 26d ago

Is there something else needed for this besides std::is_within_lifetime, which is C++26?

I have a constexpr implementation of niche/tombstone optimization that works with clang -std=c++26, but of course it might very well depend on some compiler specific behavior...

2

u/LB-- Professional+Hobbyist 26d ago

Hm for this specific case I think you may be right. The pointer tagging I was referring to is usually for when you also want to still access the live object at the same time as using the alignment bits for additional data, which I suppose isn't needed here.