只有打好基础才能写出高质量的程序,只有搞清楚了变量到底是建立在栈上的,还是建立在堆上才能有效避免内存泄漏。
看这个例子:
#include <stdio.h>
class test
{
public:
test(){printf("constructor/n");}
test(int a){printf("aconstructor/n");}
~test(){printf("destructor/n");}
};
int main()
{
test a; // 1
test *b; // 2
test c(); // 3
test d(1); // 4
test *e = new test(); // 5
return 0;
}
输出
1:
constructor
destructor
栈上局部变量
2:
无输出
BSS段
3:
无输出
编译器警告: 仅仅是变量定义?
4:
aconstructor
destructor
仍然是局部变量,栈上自动处理
5:
constructor
堆上分配,未调用析构,内存泄漏!