This is not allowed, as described here: Why is it undefined behavior to delete[] an array of derived objects via a base pointer?
Excerpt: C++03 Standard under 5.3.5 [expr.delete] p3
: 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
I also made, out of curiosity, logging version:
#include <iostream>
class A {
public:
A() {}
virtual ~A(){ std::cout << m_d << " ; ";}
double m_d {0.5};
};
class B : public A {
public:
B() {}
virtual ~B(){ std::cout << x << " : "; }
int x {2};
};
int main()
{
A* ptr = new B[5];
delete[] ptr;
std::cout << "Hi, nothing crashed here!\n";
return 0;
}
https://godbolt.org/z/Y7xGdKd3f
Clang: calls base class destructor using incorrect data
2.07634e-317 ; 0.5 ; 9.88131e-324 ; 2.07634e-317 ; 0.5 ; Hi, nothing crashed here!
Gnu: politely crashes
Program returned: 139
M$: works as expected :)
2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; 2 : 0.5 ; Hi, nothing crashed here
B*
? – ElwinaA* ptr = new B[5];
yeah that's a bad idea. The 2 objects have different sizes so any attempt to access anything other thanptr[0]
will fail horribly – Sudandelete[] ptr;
invokes undefined behavior becauseptr
points to an array ofB
objects, not an array ofA
objects – SudanB
is-aA
an array ofB
is-not-a array ofA
. – Miticide