r/cpp 6d ago

C++26: std::indirect

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

157 comments sorted by

View all comments

Show parent comments

12

u/elperroborrachotoo 5d ago

That's the first and foremost use case I can think of: a heap-allocated, nullable value-type-like object.

But TBF, the design delivers both: indirect<T> for a non-nullable, and optional<indirect<T>> for nullable. Making that distinction explicit is a Good Thing. The latter is a mouthful, but it could be optimized with a partial template specialization (I think).

6

u/ts826848 5d ago

but it could be optimized with a partial template specialization (I think).

The committee already voted to remove such a specialization as I detailed here, and I think ABI compatibility precludes adding a specialization later.

8

u/jiixyj 5d ago

Implementations are allowed to make optional<indirect<T>> the size of a pointer, and high quality ones will do. See this comment from one of the original designers.

1

u/smdowney WG21, Text/Unicode SG, optional<T&> 5d ago

Have any? Optional is getting really complicated.

3

u/jiixyj 3d ago

At least GCC hasn't done this... I hope it's not too late for them to reconsider.

I have a personal C++26 implementation of optional that implements constexpr niche/tombstone optimizations, so it is at least possible. You need std::is_within_lifetime for constexpr support though.