I found the following snippet in the C++03 Standard under 5.3.5 [expr.delete] p3
:
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 operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
Quick review on static and dynamic types:
struct B{ virtual ~B(){} };
struct D : B{};
B* p = new D();
Static type of p
is B*
, while the dynamic type of *p
is D
, 1.3.7 [defns.dynamic.type]
:
[Example: if a pointer
p
whose static type is “pointer toclass B
” is pointing to an object ofclass D
, derived fromB
, the dynamic type of the expression*p
is “D
.”]
Now, looking at the quote at the top again, this would mean that the follwing code invokes undefined behaviour if I got that right, regardless of the presence of a virtual
destructor:
struct B{ virtual ~B(){} };
struct D : B{};
B* p = new D[20];
delete [] p; // undefined behaviour here
Did I misunderstand the wording in the standard somehow? Did I overlook something? Why does the standard specify this as undefined behaviour?
(vector<B*> v(N)) == (B* p = new B[N])
. Without that, this question now makes no sense whatsoever. :| – Dissipateddelete[]
an array of derived objects via a base pointer?" – Ameeameer