1、C malloc 和 free vs C++ new 和delete:
C 语言的malloc() 和free() 并不会调用析构函数和构造函数。C++的 new 和 delete 操作符 是 "类意识" ,并且当调用new的时候会调用类的构造函数和当delete 调用的时候会调用析构函数。
下面一个例子
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class SS
- {
- public:
- SS();
- ~SS();
- private:
- int ff;
- int gg;
- };
- SS::SS()
- {
- ff=5;
- cout << "Constructor called" << endl;
- }
- SS::~SS()
- {
- cout << "Destructor called" << endl;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- SS *ss;
- ss = new SS; // new operator calls constructor.
- delete ss; // delete operator calls destructor.
- return 0;
- }
运行结果:
如图一
注意:混合用malloc 和delete或者混合用new 和free 是不正确的。C++的new和delete是C++用构造器分配内存,用析构函数清除使用过的内存。
new/delete 优点:
- new/delete调用 constructor/destructor.Malloc/free 不会.
- new 不需要类型强制转换。.Malloc 要对放回的指针强制类型转换.
- new/delete操作符可以被重载, malloc/free 不会
- new 并不会强制要求你计算所需要的内存 ( 不像malloc)
2、C 的动态内存分配:
看如下例子MallocTest.cpp
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- typedef struct
- {
- int ii;
- double dd;
- } SSS;
- int _tmain(int argc, _TCHAR* argv[])
- {
- int kk, jj;
- char *str1="This is a text string";
- char *str2 = (char *)malloc(strlen(str1));
- SSS *s1 =(SSS *)calloc(4, sizeof(SSS));
- if(s1 == NULL) printf("Error ENOMEM: Insufficient memory available\n");
- strcpy(str2,str1); //Make a copy of the string
- for(kk=0; kk < 5; kk++)
- {
- s1[kk].ii=kk;
- }
- for(jj=0; jj < 5; jj++)
- {
- printf("Value strored: %d\n",s1[jj].ii);
- }
- free(s1);
- free(str1);
- free(str2);
- }
结果:
- malloc: 用于申请一段新的地址
- calloc: 用于申请N段新的地址
- realloc: realloc是给一个已经分配了地址的指针重新分配空间
- free: 通过指针释放内存