为什么要为C ++中的抽象类声明虚拟析构函数?

我知道在C ++中为基类声明虚拟析构函数是一个好习惯,但是virtual即使对于充当接口的抽象类,声明析构函数也总是很重要吗?请提供一些原因和示例。



Smart猫小萌
浏览 957回答 3
3回答

哆啦的时光机

对于界面而言,它甚至更为重要。该类的任何用户都可能持有指向该接口的指针,而不是指向具体实现的指针。当他们删除它时,如果析构函数不是虚拟的,他们将调用接口的析构函数(如果未指定,则为编译器提供的默认值),而不是派生类的析构函数。即时内存泄漏。例如class Interface{   virtual void doSomething() = 0;};class Derived : public Interface{   Derived();   ~Derived()    {      // Do some important cleanup...   }};void myFunc(void){   Interface* p = new Derived();   // The behaviour of the next line is undefined. It probably    // calls Interface::~Interface, not Derived::~Derived   delete p; }
打开App,查看更多内容
随时随地看视频慕课网APP