class B
{
virtual ~B();
}
class D
ublic B
{
virtual ~D();
}
B *b = new D[5];
delete[] b;
Why is the above undefined.
Because the size of D is not necessarily the same as the size of B. So,
when you allocate an array of D, each object has a particular offset from
the beginning of the array. That offset along with the address of the
array forms the 'this' pointer for every object. When you want to destroy
the array, a destructor has to be called for every object. If you attempt
to destroy the array as if each element is of a different type, a slightly
different offset will be used to calculate the object addresses, and the
destructor will not be called for the correct objects. The virtualness of
the destructor has no effect on this.
Is this compiler dependent then?
Nope.
I can safely compile and run this code in VC and the destructors are
called in sequence.
So what? Undefined behaviour is just that, undefined. If it happens to
do what you expect on any particular combination of a platform/compiler,
it's pure luck. It probably can be explained (just like any other event
in nature) to some certainty, but it can't be used as the pattern to
justify any other behaviour or as a rule to expect the same behaviour on
any other platform/compiler combination.
V