1.工厂方法举例:多态基类析构函数不声明为virtual会发生什么
#include <iostream>
using namespace std;
class Base
{
public:
~Base(){}
};
class Box :public Base
{
public:
const static int s_i = 0;
};
class Box1 :public Base
{
public:
const static int s_i = 0;
};
int main() {
Base* factory1 = new Box();
Base* factory2 = new Box1();
delete factory1;
delete factory2;
return 0;
}
- 结果:内存泄漏,一共泄露sizeof(int)*2 = 8个字节 = 64bit(即派生类的内容没被释放)
2.避免内存泄漏:多态基类析构函数声明为virtual
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base(){}
};
class Box :public Base
{
public:
const static int s_i = 0;
};
class Box1 :public Base
{
public:
const static int s_i = 0;
};
int main() {
Base* factory1 = new Box();
Base* factory2 = new Box1();
delete factory1;
delete factory2;
return 0;
}
3.C++常规情况:类占用内存情况
#include <iostream>
using namespace std;
class Base
{
public:
~Base(){}
};
class Box :public Base{};
class Box1 :public Base
{
public:
double s_idd = 0.0;
};
int main() {
Base base;
Box b;
Box1 b1;
cout << sizeof(base) << endl;
cout << sizeof(b) << endl;
cout << sizeof(b1) << endl;
return 0;
}
- 输出(没有成员就占用1个字节标识自己,有成员变量就是实际成员变量的大小)
1
1
8
4.C++类无端加上虚析构函数(非多态场景)
#include <iostream>
using namespace std;
class Base
{
public:
virtual ~Base(){}
};
int main() {
Base base;
cout << sizeof(base) << endl;
return 0;
}
- 输出:(无端增加内存大小)
8
5.建议:
- 多态基类一定要写成虚析构
- 基类有一个virtual函数,析构函数也要为virtual
- 不是多态场景析构函数不要加virtual
此外:STL的类和std的类默认不是虚析构,贸然继承过来使用会内存泄漏