首页 > 代码库 > C++学习笔记25,永远将析构函数声明为virtual

C++学习笔记25,永远将析构函数声明为virtual

要永远记得将析构函数声明为virtual----><<effective c++>>

或许你觉得这句话不一定对,但无需质疑的是这句话是很有用的.

查看下面的例子:

#include <iostream>
#include <string>
using namespace std;
class B{
public:
	~B(){
		cout<<"base is destroyed!"<<endl;
	}
};
class D:public B{
public:
	~D(){
		cout<<"dirved is destroyed!"<<endl;
	}
	
};

int main(){
	{
	D d;
	}
}

这个是一个很简单的例子,输出是肯定的.

但是,再看下面的测试!

#include <iostream>
#include <string>
using namespace std;
class B{
public:
	~B(){
		cout<<"base is destroyed!"<<endl;
	}
};
class D:public B{
public:
	~D(){
		cout<<"dirved is destroyed!"<<endl;
	}
	
};

int main(){
	{
	B *b=new D();
	delete b;
	}
}

因此可以看到,当用一个基类的指针指向一个派生类的对象,直接删除该指针时,析构函数调用链将会遭到破坏.

#include <iostream>
#include <string>
using namespace std;
class B{
public:
	virtual ~B(){
		cout<<"base is destroyed!"<<endl;
	}
};
class D:public B{
public:
	virtual ~D(){
		cout<<"dirved is destroyed!"<<endl;
	}
	
};

int main(){
	{
	B *b=new D();
	delete b;
	}
}


因此应该记得将析构函数声明为virtual,这样就永远不用担心析构函数调用链遭到破坏!