r/programming • • 8d ago

Deferring sub-object construction in C with a union

https://medium.com/@christopherbazley/deferring-sub-object-construction-in-c-with-a-union-889abd08c7c2?source=friends_link&sk=ec8c79e7ae32eeaf4bb3874d948a4156
13 Upvotes

4 comments sorted by

5

u/beephod_zabblebrox 8d ago

not exactly what the post is about, but to me the issue with _Optional is exostomg headers

e.g. the vulkan api, where 99% of the you leave the pNext member of init info structs null. enabling these diagnostics would cause these errors

3

u/KAHR-Alpha 8d ago

Funnily enough, when I looked into MSVC includes, a union was used to implement std::optional in C++.

3

u/louiswins 3d ago

Making the referenced type of the parent->child.parent member _Optional merely to accommodate that intermediate state would describe a different contract from the one I want for a constructed instance of struct Child.

Why is it better for the parent to describe a different contract from the one you want merely to accommodate that intermediate state, than for the child to do the same?

It would needlessly require the pointer to be handled with care during the whole lifetime of parent, potentially requiring additional null checks or explicit removal of the qualifier at the point of use.

But now you must needlessly handle the child subobject with care during the whole lifetime of parent, because nil might be the active member instead of obj.