new/delete 和malloc/free 的区别(代码部分)

原理部分可以参见别人的博文

http://www.cppblog.com/Lee/archive/2009/03/09/75990.html

 

声明:

//NewDelete.h
#ifndef _NEWDELETE__H_
#define _NEWDELETE__H_
void TestMallocFree();
void TestNewDelete();
void TestNew();
#endif

实现:

View Code
//NewDelete.cpp
#include <stdio.h>
#include <malloc.h>
class CObject
{
public:
CObject(){
printf("Destruct0\n");
}

~CObject(){
printf("ConDestruct0\n");
}

void Init(){
printf("ConDestruct\n");
}
void Destroy(){
printf("ConDestruct\n");
}
};

class CMultDestruct
{
public:
static int c_destruct;
int m_dat;
CMultDestruct():m_dat(0)
{
c_destruct++;
printf("没有参数的构造函数,destruct cnt:%d\n",c_destruct);
}
CMultDestruct(int a):m_dat(0)//先执行初始化列表,后执行函数体
{
c_destruct++;
m_dat = a;
printf("带参数的构造函数:m_dat:%d,inpara:%d,destruct cnt:%d\n",m_dat,a,c_destruct);
}
};
int CMultDestruct::c_destruct = 0;

void TestMallocFree()
{
CObject* pObject = (CObject*)(malloc(sizeof(CObject)));
pObject->Init();
pObject->Destroy();
free(pObject);
}

void TestNewDelete()
{
CObject* pObject = new CObject;
delete pObject;
}

void TestNew()
{
//无参数的构造
CMultDestruct* p1= new CMultDestruct();

//带参数的构造
CMultDestruct* p2= new CMultDestruct(1);

//数组的构造和析构
CMultDestruct* ps1= new CMultDestruct[5];
delete []ps1;

//CMultDestruct* ps2= new CMultDestruct[5](1);//错误 编译不过去
CMultDestruct* ps3[]= {new CMultDestruct(1),new CMultDestruct(2),new CMultDestruct(3),new CMultDestruct(4),new CMultDestruct(5)};
//delete []ps3;//错误,正确的做法如下
for(int i=0;i<sizeof(ps3)/sizeof(ps3[0]);i++)
{
delete ps3[i];
}

//依靠操作系统的实例,缺点是只能在函数声明周期结束后才能被回收内存
CMultDestruct pImp;
CMultDestruct pImp2 = CMultDestruct(1);

//静态类的实例
static CMultDestruct sImp = CMultDestruct(1);
}

示例代码:

    printf("动态内存申请:\n");
TestMallocFree();
TestNewDelete();
printf("测试类的内存申请:\n");
TestNew();

运行结果:





posted on 2012-03-20 15:29  菜丝inside  阅读(211)  评论(0编辑  收藏  举报