Deleting a pointer to an incompatible type (including void
) gives undefined behaviour.
What is the solution?
- use the correct type: either the type you specified with
new
, or a base class if it has a virtual destructor; or - use
std::shared_ptr<void>
, initialised fromstd::shared_ptr<correct_type>
: its deleter will do the right thing.
In this case, it looks like you can simply store A*
rather than void*
, since you say it should be "a container for any child of class A
".
By the way, there's no need to check whether the pointer is null before deleting it.