参学:http://c.biancheng.net/cpp/biancheng/view/2978.html
c 语言中提供了 malloc 和 free 两个系统函数,完成对堆内存的申请和释放。而 c++则提供了两关键字 new 和 delete ;
1.注意:
1),new/delete 是关键字,效率高于 malloc 和 free.
2),配对使用,避免内存泄漏和多重释放。
3),避免,交叉使用。比如 malloc 申请的空间去 delete,new 出的空间被 free;
2.代码: new/delete
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
/*************1.开辟单变量地址空间*******************/
int *p = new int(5);//开辟大小为 sizeof(int)空间,并初始化为 5
cout<<"*p: "<<*p<<endl;
delete p;//释放单个 int 的空间
int *a=new int; //开辟大小为 sizeof(int)空间
*a=9;
cout<<"*a: "<<*a<<endl;
delete a;
/*****************2.开辟数组空间*********************/
/*************2.1开辟数组空间:1维*******************/
char *pp = new char[10];//开辟一个大小为 10的字符型数组空间
strcpy(pp,"china");
cout<<"pp: "<<pp<<endl;
delete []pp;// //释放char数组空间
string *ps = new string("china");//开辟大小为 sizeof(string)的空间,并初始化为 china
cout<<"*ps: "<<*ps<<endl;
cout<<"ps: "<<ps<<endl;
delete ps;
/*************2.2开辟数组空间:2维*******************/
char **pa= new char*[5];
memset(pa,0,sizeof(char*[5]));
pa[0] = "china";
pa[1] = "america";
char **pt = pa;
while(*pt)
{
cout<<*pt++<<endl;
}
delete []pt;
int (*q)[3] = new int[2][3];
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
q[i][j] = i+j;
}
}
for(int i=0; i<2; i++)
{
for(int j=0; j<3; j++)
{
cout<<q[i][j]<<" ";
}
cout<<endl;
}
delete []q;
/*************2.3开辟数组空间:3维*******************/
int (*qq)[3][4] = new int [2][3][4];
delete []qq;
}
3.附加
如果只是代码的功能,c 中的 malloc 和 free 完全可以胜任,C++就没有必要更进一步,引入这两个关键字。此两关键字,重点用在类对像的申请与释放。申请的时候会调用构造器完成初始化,释放的时候,会调用析构器完成内存的清理。