Having recently implemented the variant from N4542 the poke at the never empty variant except when a copy constructor throws was pretty amusing,
Well, the reasoning given for that seems kinda dumb:
"In the last line, v will first destruct its current value of type S , then initialize the new value from the value of type T that is held in w. If the latter part fails (for instance throwing an exception), v will not contain any valid value."
Why not keep the S value around until the copy of T has been successfully constructed? They could just construct a copy of T in a new instance of the variant, and then swap.
If you read N4542 it actually does use the temporary strategy, moving from the temporary rather than swapping. The move constructor has to throw to get the invalid state.
If index() == rhs.index(), calls get<j>(*this) = get<j>(rhs) with j being index(). Else copies the value contained in rhs to a temporary, then destructs the current contained value of *this. Sets *this to contain the same type as rhs and move-constructs the contained value from the temporary.
View all comments
Show parent comment
1
u/SushiAndWoW Jun 10 '15
Well, the reasoning given for that seems kinda dumb:
"In the last line, v will first destruct its current value of type S , then initialize the new value from the value of type T that is held in w. If the latter part fails (for instance throwing an exception), v will not contain any valid value."
Why not keep the S value around until the copy of T has been successfully constructed? They could just construct a copy of T in a new instance of the variant, and then swap.