Using virtual destructors helps ensure that the correct destructor is called
when instances of derived classes are deleted
但是还是不能区分virtual destructor和普通的destructor行为上有什么不同
哪位能举个例子出来,thx!
...全文
41011打赏收藏
virtual destructor有什么用的?
MSDN的解释如下: Using virtual destructors helps ensure that the correct destructor is called when instances of derived classes are deleted 但是还是不能区分virtual destructor和普通的destructor行为上有什么不同 哪位能举个例子出来,thx!
class A
{
public:
~A() {}
};
class B:public A
{
public:
~B() {}
};
这样话,B析构时不会去调用A的析构函数,如果A中有堆资源分配且释放在是A的析构函数中的话,B析构时就会造成内存泄漏。
用了virtual ~A()就好。
详细的内容和例子您可以参考一下Effective C++一书。
virtual destructor is mainly used like below
Base *p=new Derived;
if(no virtual destructor)
call Base destructor and will not call Derived destructor when destructing;
but *p is a object of Derived;
so it will incur memory leak;
virtual destructor will confirm that the object calls the correct destructor and be correctly destructed;