标签:
1.为多态基类声明虚析构函数
code1:
class A{
public:
int* a;
A():a(new int(5))
{}
~A(){
delete a;
}
};
class B:public A
{
public:
int *b;
B():b(new int(10))
{}
~B(){
delete b;
}
};
int main(int argc, char const *argv[])
{
B *bb=new B;
A* aa=bb;
delete aa;//bb中的部分内存泄漏
return 0;
}
code2:
class A{
public:
int* a;
A():a(new int(5))
{}
virtual ~A(){//声明为虚析构函数
delete a;
}
};
class B:public A
{
public:
int *b;
B():b(new int(10))
{}
~B(){
delete b;
}
};
int main(int argc, char const *argv[])
{
B *bb=new B;
A* aa=bb;
delete aa;//OK
return 0;
}
纯虚析构函数需要有定义,因为虚析构函数层层调用,如果最底层没有定义,那么链接会失败
2.为何不把虚构函数全部声明为虚析构函数?
会使用更多内存,馊主意
3.任何class中只要有virtrual函数,就差不多应该声明一个虚析构函数
总结:
标签:
原文地址:http://www.cnblogs.com/SkyFireITDIY/p/4376074.html