说说C++中的malloc与new 很多人都知道malloc与new都是用来申请空间用的,开辟空间来源于堆中。
但是在C++中却很少用malloc去申请空间,为什么会这样?后面会有个很有说服力的例子,相信大家一看就能明白。C++程序的格局可分为4个区,注意是“格局”, 1、全局数据区 2、代码区 3、栈区 4、堆区 其中全局变量,静态变量是属于全局数据区;所有的类和非成员函数的代码都存放在代码区;为成员函数运行而分配的局部变量的空间都在栈区,剩下的那些空间都属于堆区。 下面来写个简单的例子 #include <iostream.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)); delete p; return 0; } 编译运行:The Class have DisConstructed 结果是没有调用构造函数,从这个例子可以看出,调用malloc后,malloc只负责给对象指针分配空间,而不去调用构造函数对其初始化。而C++中一个类的对象构造,需要是分配空间,调用构造函数,成员的初始化,或者说对象的一个初始化过程。通过上述例子希望大家在使用C++中尽量不要去使用malloc,而去使用new。 #include <iostream.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"; //delete p; free (p); return 0; } 本文来源:http://blog.csdn.net/jufeng2309/archive/2007/08/28/1761828.aspx
|