为了永远记住析构函数声明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; } }
这个是一个非常easy的样例,输出是肯定的.
可是,再看以下的測试!
#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,这样就永远不用操心析构函数调用链的破坏!
版权声明:本文博主原创文章,博客,未经同意不得转载。