new和delete表示从堆区申请空间和释放空间
与malloc,calloc,realloc相比较
1.malloc返回一个void指针,c++不允许将void赋值给其他任何指针,必须强转。
2.malloc可能申请内存失败,所以必须判断返回值来确保内存分配成功。
3.malloc 不会调用构造函数。free 不会调用析构函数
new delete
1、给基本类型申请空间
void test0()
{
//基本类型
int *p = NULL;
p = new int;
*p = 100;
cout<<"*p = "<<*p<<endl;//100
delete p;
}
2、申请基本类型数组空间
void test1()
{
int *arr = NULL;
arr = new int[5]{1,2,3,4,5};
int i=0;
for(i=0;i<5;i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void test2()
{
char *p = NULL;
p = new char[32];
strcpy(p,"hehehe");
cout << p <<endl;
delete [] p;
}
注意
new 没有加[] delete释放的时候 就不加[]
new 加[] delete释放的时候 就加[]
3、给类对象申请空间
void test4()
{
Person *p = new Person("lucy",18);
p->display();
delete p;
}
对象数组
本质是数组,数组元素是类的对象
如果想让对象数组中的元素调用有参构造 必须人为使用 有参构造初始化。
void test5()
{
Person arr1[5] = {Person("lucy",18),Person("bob",19),Person("tom",20)};
arr1[0].display();
arr1[1].display();
arr1[2].display();
}
用new delete申请 对象数组
void test08()
{
//第一种方式
Person *arr = NULL;
arr = new Person[5];//调用无参构造
delete [] arr;
//第二种方式:
//初始化的元素 调用有参构造 没有初始化 的调用无参构造
Person *arr2 = new Person[5]{Person("lucy",18), Person("bob",20)};
(*(arr2+0)).showPerson();
arr2[0].showPerson();
(arr2+1)->showPerson();
delete [] arr2;
}