Does “delete” work properly with polymorphism? [duplicate]

偶尔善良 提交于 2019-12-05 20:38:59

Well in the case that it has a virtual destructor, of course the object will be destroyed and the memory deallocated as expected. If it doesn't have a virtual destructor, the behaviour is undefined.

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 dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

So it doesn't really make any sense to attempt to reason about whether the memory will be fully deallocated or not. The program can do whatever it likes with the memory.

If the destructor isn't virtual, delete won't delete the derived class.

I tried this:

#include<iostream>

using namespace std;

class Base {
public:
    Base() {
        cout<<"Creating base."<<endl;
    }

    ~Base() {
        cout<<"Killing base."<<endl;
    }
};

class Derived: public Base {
public:
    Derived() {
        cout<<"Creating derived."<<endl;
    }

    ~Derived() {
        cout<<"Killing derived."<<endl;
    }
};

int main() {
    Base *p = new Derived();
    delete p;
    return 0;
}

Compiling on G++ 4.7.3 (default optimization), I get

Creating base.
Creating derived.
Killing base.

Note the absence of Killing derived.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!