虚析构函数可以解决基类的指向派生类对象,并用基类的指针直接释放派生类对象的问题。
当一个类不准备作为基类使用时,使用虚析构函数并不是一个好主意。因为不作基类的情况下,这个类就没有必要定义其他虚函数,采用虚析构函数会为类增加一个虚函数表指针的长度,使得类对象占用的空间增加,还有可能降低其可移植性。如下代码所示:
#include "stdafx.h"
class Base
{
public:
~Base()
{
printf("The Base Destructor is Called!\n");
}
};
int main()
{
int sz = sizeof(Base);
printf("sizeof Base = %d\n",sz);
///
getchar();
return 0;
}
备注:对于没有成员变量的类,默认会补充一个char的长度,所以长度为1。
将其析构函数改为虚析构函数后,其长度变为了4,空间有所增加,代码如下。
#include "stdafx.h"
class Base
{
public:
virtual ~Base()
{
printf("The Base Destructor is Called!\n");
}
};
int main()
{
int sz = sizeof(Base);
printf("sizeof Base = %d\n",sz);
///
getchar();
return 0;
}
虚析构函数的典型应用代码如下:
#include "stdafx.h"
///
class Base
{
public:
virtual ~Base()
{
printf("The Base Destructor is Called!\n");
}
};
//
class Child:public Base
{
public:
~Child()
{
printf("The Child Destructor is Called!\n");
}
};
///
class SubChild:public Child
{
public:
~SubChild()
{
printf("The subChild Destructor is Called!\n");
}
};
///
class Sub2Child:public SubChild
{
public:
~Sub2Child()
{
printf("The Sub2Child Destructor is Called!\n");
}
};
/// -------------------------
int main()
{
Base *pBase = new Sub2Child;
if(pBase)
{
delete pBase;
pBase = NULL;
}
///
getchar();
return 0;
}
只需要把基类析构函数变为虚析构函数,将子类的(可能是多级继承)对象赋给基类指针,释放基类的指针也会触发到子类的析构函数调用。结果如下:
如果是非虚析构函数的话,将只会释放基类的指针,代码如下:
#include "stdafx.h"
///
class Base
{
public:
~Base()
{
printf("The Base Destructor is Called!\n");
}
};
//
class Child:public Base
{
public:
~Child()
{
printf("The Child Destructor is Called!\n");
}
};
///
class SubChild:public Child
{
public:
~SubChild()
{
printf("The subChild Destructor is Called!\n");
}
};
///
class Sub2Child:public SubChild
{
public:
~Sub2Child()
{
printf("The Sub2Child Destructor is Called!\n");
}
};
/// -------------------------
int main()
{
Base *pBase = new Sub2Child;
if(pBase)
{
delete pBase;
pBase = NULL;
}
///
getchar();
return 0;
}
如果子类的析构函数为虚析构函数,那么要求其基类也应该定义虚析构函数。代码如下:
#include "stdafx.h"
///
class Base
{
public:
~Base()
{
printf("The Base Destructor is Called!\n");
}
};
//
class Child:public Base
{
public:
virtual ~Child()
{
printf("The Child Destructor is Called!\n");
}
};
///
int main()
{
Base *pBase = new Child;
if(pBase)
{
delete pBase;
pBase = NULL;
}
///
getchar();
return 0;
}
这种情况下,打印结果为只调用基类的虚析构函数,且还会有程序异常。
19万+

被折叠的 条评论
为什么被折叠?



