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> != trueand*thiscontains a value, callsval->T::~T().
2 Remarks: Ifis_trivially_destructible_v<T> == truethen 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().
std::optional already has constexpr constructors. When its destructor is trivial, it is a literal type. Only objects of literal types can be created and manipulated in constant expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With