The standard mandates that the move assignment operator of optional
...
constexpr optional& operator=( optional&& other )
[...] shall not participate in overload resolution unless
is_move_constructible_v<T>
is true andis_move_assignable_v<T>
is true.
The assignment of an optional value lhs = rhs;
does either
- destroy
lhs
(ifbool(lhs) && !bool(rhs)
) - construction
lhs
fromrhs
(if!bool(lhs) && bool(rhs)
) or - assign
rhs
tolhs
(ifbool(lhs) && bool(rhs)
).
Thus, it would have been an option to have two sets of preconditions for move assignment of optional
:
is_move_constructible_v<T> && is_move_assignable_v<T>
is_move_constructible_v<T> && is_copy_assignable_v<T>
Where the second form could use copy assignment if bool(lhs) && bool(rhs)
but move construction if !bool(lhs) && bool(rhs)
.
I see an admittedly rather artificial issue with the current set of preconditions with respect to the following two classes of types:
A type which is not move assignable but copy assignable, move constructible and copy constructible can not benefit from move construction on assignment, eventhough construction is part of the assignment operation. The
optional
copy assignment operator will be selected and copy construct or copy assign the value.A type which is neither copy constructible nor move assignable but move constructible and copy assignable cannot be assigned at all.
Is this something that has been considered during the standardization process for optional
or is there any rationale why it has not been considered or has been waived?
(Disclaimer: I know that is_move_assignable
is usually true if is_copy_assignable
is true unless the move assignment operator is explicitly deleted.)
is_move_constructible_v<T> && is_move_assignable_v<T> == is_move_constructible_v<T> && is_copy_assignable_v<T>
so it's not needed. As show here an implicitly deleted move assignment operator is still move assignable as long as the copy assignment operator is not deleted. – Heteropterousis_move_assignable<T>
false, regardless of the presence of copy assignment. There is a reason I wrote that the problem is "rather artificial". – SelloCopyConstructible
subsumesMoveConstructible
. – Mariannemariano