Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could deleting complete class type result in undefined behavior?

I find myself have troubles in understanding following sentence quoted from C++ standard in 5.3.5$5: (emphasis is mine)

If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

I know this deleting incomplete type problem has been discussed several times in SO, and I can understand why deleting incomplete class type is undefined behavior. This Q&A explains it very well.

What I can't understand is the part about complete class type. Does it mean deleting a object of complete class has a non-trivial destructor or a deallocation function is undefined behavior? If so, please give some codes illustrating the undefined behavior that it could result in.

like image 207
Carousel Avatar asked Dec 29 '25 00:12

Carousel


1 Answers

There are two prerequisites for undefined behavior in the concerned case:

  1. Object is being deleted through a pointer to an incomplete type;
  2. The complete class of the object being deleted has a non-trivial destructor or a (user-defined) deallocation function.

If either of these conditions is false, then there is no undefined behavior (at least due to the concern being discussed).

This in particular means that

  1. Deleting an object of complete type is safe (because the right destructor and/or deallocation function will be executed).

  2. Deleting an object with a trivial destructor and without a user-defined deallocation function through a pointer to an incomplete type is safe (because in the absence of complete type information the compiler doesn't call the destructor and uses the default deallocation function, which perfectly matches what would happen had the deletion be performed through a pointer to complete type).

like image 156
Leon Avatar answered Dec 30 '25 16:12

Leon



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!