Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of trivial destruction

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: If is_trivially_destructible_v<T> != true and *this contains a value, calls val->T::~T().
2 Remarks: If is_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().

like image 647
Barry Avatar asked Jan 27 '17 15:01

Barry


1 Answers

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.

like image 176
cpplearner Avatar answered Sep 29 '22 13:09

cpplearner