Virtual destructor failure

I found this code on the website

#include <iostream>

using namespace std;

struct Base
{
    Base() { cout << "Base" << " "; }
    virtual ~Base() { cout << "~Base" << endl; }

    int i;
};
struct Der : public Base
{
    Der() { cout << "Der" << endl; }
    virtual ~Der() { cout << "~Der" << " "; }

    int it[10]; // sizeof(Base) != sizeof(Der)
};

int main()
{
    Base *bp = new Der;
    Base *bq = new Der[5];

    delete    bp;
    delete [] bq;   // this causes runtime error
}

why is he crash ?

+5
source share
1 answer
Base *bq = new Der[5];
delete [] bq;   // this causes runtime error

The reason is that arrays are not processed polymorphically. Therefore, in the above code, the operator deleteinvokes undefined behavior .

§5.3.5 / 3 C ++ 03 says

( ), , , undefined. ( ), , undefined.

, , .

+9

All Articles