使用具有权威说服力的实例辨明C++中的malloc与new
问题:
很多人都知道malloc与new都是用来申请空间用的,开辟空间来源于堆中。但是在C++中却很少用malloc去申请空间,为什么?
下面小编会以一个很有说服力的例子来说明,相信大家一看就能明白。
C++程序的格局可分为4个区,注意是“格局”,
1、全局数据区 //其中全局变量,静态变量是属于全局数据区
2、代码区 //所有的类和非成员函数的代码都存放在代码区
3、栈区 //为成员函数运行而分配的局部变量的空间都在栈区
4、堆区 //剩下的那些空间都属于堆区
其中全局变量,静态变量是属于全局数据区;所有的类和非成员函数的代码都存放在代码区;为成员函数运行而分配的局部变量的空间都在栈区,剩下的那些空间都属于堆区。
下面来写个简单的例子:malloc.cpp
#include <iostream>
using namespace std;
#include <stdlib.h>
class Test{
public:
Test(){
cout<<"The Class have Constructed"<<endl;
}
~Test(){
cout<<"The Class have DisConstructed"<<endl;
}
};
int main(){
Test *p = (Test*)malloc(sizeof(Test));
free(p);
//delete p;
return 0;
}
编译运行:The Class have DisConstructed
结果是没有调用构造函数,从这个例子可以看出,调用malloc后,malloc只负责给对象指针分配空间,而不去调用构造函数对其初始化。而C++中一个类的对象构造,需要是分配空间,调用构造函数,成员的初始化,或者说对象的一个初始化过程。通过上述例子希望大家在使用C++中尽量不要去使用malloc,而去使用new。
<span style="font-size:14px;">#include <iostream>
using namespace std;
#include <stdlib.h>
class Test{
public:
Test(){
cout<<"The Class have Constructed"<<endl;
}
~Test(){
cout<<"The Class have DisConstructed"<<endl;
}
};
int main(){
//Test *p = (Test*)malloc(sizeof(Test));
Test *p = new Test;
cout<<"test"<<endl;
//free(p);
delete p;
return 0;
}</span>
运行结果如下:
如果想更加系统了解C++ new/delete,malloc/free的异同点,可以参看“深入C++ new/delete,malloc/free解析”了解详情。The Class have Constructed
The Class have DisConstructed