虚函数与多态一文中讲了虚函数的用法和要点,但少讲了一点,就是虚函数在析构中的用法,本文就是修复一bug的。
C++类有继承时,析构函数必须为虚函数。如果不是虚函数,则使用时可能存在内在泄漏的问题。
假设我们有这样一种继承关系:
如果我们以这种方式创建对象:
SubClass* pObj = new SubClass();
delete pObj;
不管析构函数是否是虚函数(即是否加virtual关键词),delete时基类和子类都会被释放;
如果我们以这种方式创建对象:
BaseClass* pObj = new SubClass();
delete pObj;
- 若析构函数是虚函数(即加上virtual关键词),delete时基类和子类都会被释放;
- 若析构函数不是虚函数(即不加virtual关键词),delete时只释放基类,不释放子类;
测试代码
大家可以自己测试一下,以下是我的测试代码:
#include <string>
#include <iostream>
class BaseClass
{
public:
BaseClass()
: m_pValue(NULL)
{
}
/*virtual */~BaseClass()
{
delete m_pValue;
m_pValue = NULL;
std::cout << "BaseClass virtual construct." << std::endl;
}
void SetValue(int v)
{
if (!m_pValue)
{
m_pValue = new int(v);
}
else
{
*m_pValue = v;
}
}
private:
int* m_pValue;
};
class SubClass : public BaseClass
{
public:
SubClass()
: BaseClass()
, m_pstrName(NULL)
{
}
/*virtual */~SubClass()
{
delete m_pstrName;
m_pstrName = NULL;
std::cout << "SubClass virtual construct." << std::endl;
}
void SetName(const std::string& name)
{
if (!m_pstrName)
{
m_pstrName = new std::string(name);
}
else
{
*m_pstrName = std::string(name);
}
}
private:
std::string* m_pstrName;
};
int main()
{
BaseClass* pObj = new SubClass();
pObj->SetValue(10);
((SubClass*)pObj)->SetName("zhangsan");
delete pObj;
pObj = NULL;
return 0;
}