c++language-lawyerdestructor

Why does a virtual default destructor make a class non-trivially-destructible?


Out of curiosity, why is a class containing a defaulted virtual destructor considered as non-trivially-destructible?

#include <type_traits>

struct X
{
   virtual ~X() = default;
};

static_assert(std::is_trivially_destructible_v<X>); // Fails

A quote from cppreference.com:

Objects with trivial destructors don't require a delete expression and may be disposed of by simply deallocating their storage

The only thing the destructor does is it changes the VMT_PTR to the Base::VMT_PTR (if there is a base). If you decide to not invoke that destructor, nothing bad happens.


Solution

  • Consider:

    main.cpp

    X* from_somewhere();
    
    int main() {
        X* x = from_somewhere();
        delete x;
    }
    

    impl.cpp

    struct Y : X {
        std::string name;
    }
    X* from_somewhere() { return new Y; }
    

    Does anything need to be done before freeing the storage of *x? If yes, then clearly X::~X isn't trivial.