r/cpp • u/_VZ_ wx | soci | swig • Jun 17 '15
Standardizing Variant: Difficult Decisions
https://www.justsoftwaresolutions.co.uk/cplusplus/standardizing-variant.html
26
Upvotes
r/cpp • u/_VZ_ wx | soci | swig • Jun 17 '15
View all comments
Show parent comment
1
u/[deleted] Jun 18 '15 edited Jun 18 '15
So suppose I want to assign a new type to the variant:
I copy construct it into a stack buffer. That might throw.
If it throws, the old type remains in the variant. Yay!
If it doesn't throw, I first destroy the type in the variant; this is required not to throw. Then I have to copy/move assign the new type from the stack buffer of the copy constructor into the variant buffer (because the stack buffer of the copy constructor is destroyed at function exit). But this operation can throw, so this just delays the problem.
I thought that move constructor could be required not to throw but as Eric pointed out above, they can for some types (like all the node-based containers in the STL).
By requiring the second buffer to be in the variant, the second copy/move construction is not necessary, so if the first one succeeds, we just change the "active" buffer of the variant to be the new one (in a way that cannot throw), and destroy the type in the old one.