r/cpp • • Aug 13 '26

C++26: std::indirect

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

157 comments sorted by

View all comments

30

u/fdwr fdwr@github 🔍 Aug 13 '26 edited Aug 14 '26

std::indirect - Hmm, it feels like a noun is missing after the adjective (an indirect ... what?), which would be like std::unique without the ptr. Though, I suppose in context (e.g. std::indirect<Settings>) it makes sense, because you can read the copyable pointer like "an indirect Settings object".

I've definitely wanted this before to fill the hole in std, something with cardinality 0-1 in between std::optional (which always embeds the optional object regardless of whether present or not, but is copyable) and std::unique_ptr (where you don't pay for the space if unused, but it doesn't allow cloning). Currently all the other candidates have some limitations:

Update: u/jiixyj educated me that std::indirect is actually cardinality 1 (with "valueless" being a special empty state rather than a default useable state like optional/unique_ptr/shared_ptr/vector...).

ClassRAIIAllocatedCardinal 0-1CopyableMinimal overheadDirect access
std::vector✅✅❌ 0-N✅ copyable❌ has capacity and size✅ object[0]
std::list✅✅❌ 0-N✅ copyable❌ extra links❌
std::any✅✅✅ 0-1✅ copyable❌ overkill RTTI❌ requires any_cast
std::optional✅❌✅ 0-1✅ copyable✅ single bool field✅ *object
raw pointer❌✅✅ 0-1❌ shared✅ just a pointer✅ *object
std::shared_ptr✅✅✅ 0-1❌ shared❌ has control block✅ *object
boost::intrusive_ptr✅✅✅ 0-1❌ shared❌ reference count✅ *object
std::unique_ptr✅✅✅ 0-1❌ noncopyable✅ just a pointer✅ *object
stdex::copyable_ptr✅✅✅ 0-1✅ copyable✅ just a pointer✅ *object
std::indirect✅✅❌ 1✅ copyable✅ just a pointer✅ *object

17

u/jiixyj Aug 14 '26

For indirect the cardinality should be 1 instead of 0-1. The valueless_after_move() state is just an artifact of C++'s move semantics.

It's the same reason a variant<Red, Blue> really just is the union of all possible Red and all possible Blue values, despite the existence of the valueless_by_exception() state.

2

u/fdwr fdwr@github 🔍 Aug 14 '26 edited Aug 14 '26

For indirect the cardinality should be 1

Doh, well in that case, std::indirect may not be quite what I need for my scenarios, because I basically want an optional except the space is not wasted when the heavy object isn't present, where empty is a valid object state. Then guess I'll keep my copyable_ptr class still. Added a new row in the table ⬆️.

6

u/SlightlyLessHairyApe Aug 15 '26

optional indirect is exactly right here.

Edit: you do have to distinguish unengaged vs engaged & moved-from

2

u/SoerenNissen Aug 15 '26

It rather doesn't matter where valueless_after_move comes from, there's a state where it doesn't hold 1×T.

-1

u/sosogg_4 Aug 15 '26

Thanks for the summary bro