现在的位置: 首页 > 综合 > 正文

C++学习笔记15 malloc free 与 new delete的区别

2016年02月04日 ⁄ 综合 ⁄ 共 848字 ⁄ 字号 评论关闭
#include <iostream>
#include <cstdlib>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;


class Test
{
	int i;
	public:
		
		Test()
		{
			cout<<"Test( )"<<endl;
			i = 0;
		}
		Test(int i)
		{
			cout<<"Test(int i)"<<endl;	
			this->i = i;	
		}
		~Test()
		{
			cout<<"~Test()"<<endl;
		}
		int getI()
		{
			return i;
		}
		
		
	
};
void func()
{
	int * p = reinterpret_cast<int*>(malloc(sizeof(int)));
	//int * q = new int;
	int *q = new int(10);//new 可以初始化,malloc不可以 
	
	
	*p = 5;
	//*q = 10;
	
	cout<<*p<<endl<<*q<<endl;
	
	free(p);
	delete q;
	
	
	Test * op = reinterpret_cast<Test*>(malloc(sizeof(Test)));//malloc没办法调用构造函数构造对象,只是负责单纯的申请一段空间 
	Test * oq = new Test;//不但申请空间,还主动调用构造函数创建对象。 
	
	cout<<op->getI()<<endl<<oq->getI()<<endl;
	
	free(op);
	delete oq;//如果这里使用  free(oq)发现少了析构函数的调用 
	
	
} 

int main(int argc, char** argv) {
	
	func();
	
	return 0;
}

/*
malloc和free是库函数,以字节为单位申请堆内存
new和delete是关键字,以类型为单位申请堆内存
malloc和free单纯的对内存进行申请与释放
对于基本类型new关键字会对内存进行初始化
对于类类型new和delete还负责构造函数和析构函数的调用
*/ 

抱歉!评论已关闭.