一、malloc(库函数)在C++中的作用
单纯的申请一块内存,不执行对象的建立(没有调用构造函数)
#include <iostream>
#include <cstdlib>
using namespace std;
class Test
{
public:
Test()
{
cout <<"Test 构造函数" << endl;
}
~Test()
{
cout <<"Test 析构函数" << endl;
}
};
int main()
{
Test t1; //栈空间创建对象
//创建对象 1、申请空间 2、调用构造函数初始化 c++不用malloc创建对象
Test *pt = (Test *)malloc(sizeof(Test) * 1); //在堆空间申请一个对象大小的内存
if(NULL == pt)
{
cout << "malloc failure" << endl;
}
free(pt); //释放内存,不释放对象
return 0;
}
二、new和delete(关键字:运算符)用法
作用:创建堆内存对象,类似于malloc,但是可以自动启动类构造函数
1、new用法:
Test *pt2 = new Test;
2、delete用法
delete pt2;
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout <<"无参构造函数" << endl;
}
Test(int a,int b)
{
cout <<"有参构造函数" << endl;
}
~Test()
{
cout << "析构函数" << endl;
}
};
int main()
{
int *p1 = new int; //给一个整数申请空间
cout << *p1 << endl;
delete p1; //不delete会可能内存泄漏
char *p2 = new char; //给一个字符申请空间
delete p2;
int *p3 = new int(100); //给一个整数申请空间 同时初始化100
cout << *p3 << endl;
delete p3;
char *p4 = new char[10]; //给10个字符申请空间 数组
delete[] p4; //释放数组加上[]
Test *t1 = new Test;
delete t1;
Test *t2 = new Test(1,2);
delete t2;
return 0;
}