In C++17, the new std::optional
mandates that it be trivially destructible if T
is trivially destructible in [optional.object.dtor]:
~optional();
1 Effects: Ifis_trivially_destructible_v<T> != true
and*this
contains a value, callsval->T::~T()
.
2 Remarks: Ifis_trivially_destructible_v<T> == true
then this destructor shall be a trivial destructor.
So this potential implementation fragment would be non-conforming to the standard:
template <class T>
struct wrong_optional {
union { T value; };
bool on;
~wrong_optional() { if (on) { value.~T(); } }
};
My question is: what is the advantage of this mandate? Presumably, for trivially destructible types, the compiler can figure out that value.~T()
is a no-op and emit no code for wrong_optional<T>::~wrong_optional()
.