vendredi 24 avril 2015

Is it safe to delete POD object by 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) 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...

Aucun commentaire:

Enregistrer un commentaire