Why is delete[] basePtr undefined if basePtr points to array of derived-class objects

P

pareshgoel

class B
{
virtual ~B();
}

class D:public B
{
virtual ~D();
}

B *b = new D[5];
delete[] b;

Why is the above undefined.
Is this compiler dependent then?
I can safely compile and run this code in VC and the destructors are
called in sequence.
 
V

Victor Bazarov

class B
{
virtual ~B();
}

class D:public 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
 
D

Divick

Well in the above mentioned example, the sizes of both the classes are
same and does work with g++ as well while if you start adding members
to the classes such that the size differ then it crashes.

Divick
 
J

John Harrison

Divick said:
Well in the above mentioned example, the sizes of both the classes are
same and does work with g++ as well while if you start adding members
to the classes such that the size differ then it crashes.

Divick

Newbies often find this a hard concept to grasp. Undefined behaviour
means that the C++ standard does not define any behaviour. That means
that it might work on one compiler, but it might crash on another. Both
compilers are right because the behaviour is undefined. Also it might
work in one situation (e.g. when the classes have the same size) but not
in another.

Who knows, it might work on a Wednesday but not on a Tuesday because the
behaviour is *undefined*.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top