Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to delete a POD object by a pointer to its base?

Actually I am thinking about trivially destructible objects, not only about POD (I am not sure POD can have base class).

When I read this explanation for is_trivially_destructible from cppreference I notice this:

Storage occupied by trivially destructible objects may be reused without calling the destructor.

So, it is safe to do that:

struct A {
  int a;
};
struct B : A {
  int b;
};
int main() {
  A* a = new B;
  delete a;
}

B::~B() won't be called - and AFAIK (please correct if I am wrong) the entire memory will be freed. And B::~B() for sure is trivial.

I know this code smells badly, but my question is only about safeness of this code...

like image 361
PiotrNycz Avatar asked Apr 24 '15 07:04

PiotrNycz


1 Answers

No, this is not allowed. [expr.delete]/p3, emphasis mine:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

In fact, the committee fairly recently rejected a proposal to make deleting a POD via a pointer-to-base well-defined.

like image 100
T.C. Avatar answered Oct 11 '22 15:10

T.C.