在C++的多态中,要注意new和delete对象的类型要保持一致
父类有纯虚函数,子类分别继承和实现了纯虚函数。为了实现多态,在调用函数中,声明的是指向父类的指针,实际new出来的是子类的对象。
在new出来的过程中,因为继承关系,所以先后执行了父类的构造函数和子类的构造函数。
但是,在delete此对象的时候,如果不指明何种类型,很可能是按照父类对象来析构的,即仅执行父类的析构函数。这样,很有可能造成内存泄漏,甚至程序宕机。
···
class A
{
public:
A()
{
cout << "\t\t\tA() - constructor of parent class\n";
}
~A()
{
cout << "\t\t\t~A() - destructor of parent class\n";
}
virtual void run() = 0;
};
class B : public A
{
public:
B()
{
cout << "\tB() - constructor of child class\n";
}
~B()
{
cout << "\t~B() - destructor of child class\n";
}
void run()
{
cout << "running in sub-class B\n";
}
};
class C : public A
{
public:
C()
{
cout << "\C() - constructor of child class\n";
}
~C()
{
cout << "\t~C() - destructor of child class\n";
}
void run()
{
cout << "running in sub-class C\n";
}
};
void minCode()
{
A* b1 = NULL;
b1 = new B;
b1->run();
cout << "I'll delete object b1\n";
delete b1;
//delete static_cast<B*>(b1);
b1 = new C;
b1->run();
cout << "I'll delete object b1 again!\n";
//delete b1;
delete static_cast<B*>(b1);
}
void main()
{
minCode();
cout << "\n\n===================\nApp is closing...\n";
system("pause");
}
···
所以,在遇到这种情况时,尤其要注意,new的时候是何种类型,delete时也要用何种类型来释放。