Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
Dmytro Ovdiienko Avatar asked Oct 31 '25 21:10

Dmytro Ovdiienko


1 Answers

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.

like image 99
Caleth Avatar answered Nov 03 '25 10:11

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!