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

1

13

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...

Bunchy answered 24/4, 2015 at 7:59 Comment(5)
Are you sure that a will always point to a B instance and that B is going to remain trivially destructible? If someone modifies B or replaces it with a non-trivially destructible subclass of B he will silently introduce a bug.Tarbox
I don't quite get the point you are aiming for. If you wanted to re-use a heap-allocated object, you would not free the heap memory (coming along with the delete call) but you would keep the unused instance in some sort of recycling container instead of calling delete on it. You would probably also have a "factory" method to obtain an instance, which would first try to recycle old instances before it creates new instances with new.Landman
Scratch my previous post lol. He asked about whether he needs a virtual destructor without ever using those words :)Landman
@Tarbox - not I am not sure that. And you are right - that will be a bug. But for this very question assume all involved types are trivially destructible.Bunchy
Is it even still POD if it uses inheritance?Flinger
P
19

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.

Prefab answered 24/4, 2015 at 8:7 Comment(1)
Perhaps worth mentioning is whether explicitly calling ::operator delete(a) is a valid workaround. As far as I can see, that would be valid. I wouldn't recommend it, though, if there is any possibility that delete a; would actually have called a different operator delete.Scatter

© 2022 - 2024 — McMap. All rights reserved.