一: 记住带多态性质的base class 应该申明为virtual 析构函数 , 如果class 中至少有一个virtual 的成员函数,这时候它应该拥有一个virtual 析构函数。
二:若class 的设计目的不是为了base class 使用 , 或者不是为了具备多态性, 就不应该申明为virtual 析构函数。
1. 基类使用virtual 析构函数的情况:
假设base class 为 Window , 而它有多种形式的窗口来显示,例如ScrollWindow , EditWindow , DialogWinow ....... ;
这时它应该为了具备多态的性质而设计,此时它应该有一个virtual 析构函数
class Window
{
public:
Window()
{
cout<<"Window constructor Called."<<endl ;
}
~Window()
{
cout<<"Window destructor Called."<<endl ;
system("pause") ;
}
} ;
class ScrollBarWindow : public Window
{
public:
ScrollBarWindow()
{
cout<<"ScrollBarWindow constructor Called."<<endl ;
}
~ScrollBarWindow()
{
cout<<"ScrollBarWindow destructor Called."<<endl ;
system("pause") ;
}
} ;
其运行结果为:
Window constructor Called.
EditWindow constructor called.
Window destructor Called.
请按任意键继续. . .
你如果把各个Class的 析构函数申明为virtual 的话,这个资源泄漏的问题就可以迎刃而解了,其结果为:
Window constructor Called.
EditWindow constructor called.
EditWindow destructor called.
Window destructor Called.
请按任意键继续. . .
答案符合常理.
2.class 无需用virtual 析构函数的情况:
现在我们要建立一个空间坐标的类Class Point
class Point
{
public:
Point(int x , int y) ;
~Point() ;
private:
int m_x , m_y ;
} ;
如果一个int占32bits ,那么这个Point 总共占64bits , 如果你的Point的析构函数用的virtual 析构函数, 那么每一个类都有一个相应的vtbl(virtual table),通过vptr(virtual table pointer )来进行函数寻址, 这时Point 对象的大小就不是64bits了, 应该加上一个指针64bits ,所以总的大小为128bits,因而, 它不能被塞入一个64bits的缓存器了,故,他就不能被传递至其它语言所写的函数,从而没有移植性!!