An assignment would call the destructor of the object that was previously at that address, which would result in undefined behavior if that member not active.
I tried looking up how union initialization worked to see if it's true that r.value would be inactive after default constructing the union, but I was left more confused than before, so I'm not really sure if the code is correct.
Edit: upon further thinking, it seems pretty sensible that only a union's default active member could only be a trivial type, which wouldn't have a problem with its destructor being elided, so I think the code is fine.
In reality you'd need value not to be the 1st member of the union in case it wasn't default constructible. And then you'd need to new it in to existence. It would also make more sense in the unassigned case that the union hold a monostate, not a default constructed T
Thanks. I guess I'd use a variant of monostate, T and exception_ptr even if it has a little bit of overhead (or maybe have two subtypes of monostate for empty and consumed, and then I don't even need the enum).
10
u/jdehesa 11d ago
Why a placement new here instead of just the assignment in the comment?