开发者

virtual destructor fail using array

开发者 https://www.devze.com 2023-04-13 06:30 出处:网络
I found this code on a web site #include <iostream> using namespace std; struct Base { Base() { cout << \"Base\" << \" \"; }

I found this code on a web site

#include <iostream>

using namespace std;

struct Base
{
    Base() { cout << "Base" << " "; }
    virtual ~Base() { cout << "~Base" << endl; }
开发者_StackOverflow中文版
    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 does it crash?


Base *bq = new Der[5];
delete [] bq;   // this causes runtime error

The reason is arrays are not treated polymorphically. Therefore, in the above code, the delete statement invokes undefined behaviour.

§5.3.5/3 C++03 says

In the first alternative (delete object), if the static type of the operand 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.

You're lucky that it gives runtime-error, and you got the opportunity to know a serious bug in your code, as soon as possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号