在C++中也有和C语言的一样有专有的动态开辟空间操作符,C++的专有动态操作符是使用new操作符来开辟,配套的释放空间使用的是delete。但是初学C++的很多人只知道new操作符的简单使用,不知道new还有三种操作符,他们也有着不同的作用和使用方法,它们分别是new operator、operator new和placement new,还有一个在动态申请空间申请出错设置处理函数而不会使程序崩掉,下面我们来看看C++下面new操作符的这四个属性的具体实现:
1、new operator
功能:
1)申请空间
2)构造对象
3)delete对象的时候, 先析构 再释放
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Create Test Object ."<<endl;
data = malloc(sizeof(int)*10);
}
~Test()
{
free data;
}
public:
void * operator new(size_t sz)//重载new必须返回时void*,第一个参数必须是size_t类型
{
void * p = malloc(sz);
assert(*p != NULL);
return p;
}
void oprator delete(void *p)
{
free p;
}
private:
int *data;
};
void * operator new(size_t sz)
{
void * p = malloc(sz);
assert(*p != NULL);
return p;
}
void oprator delete(void *p)
{
delete p;
}
int main()
{
Test *p = new Test;//调用operator new 调用对象构造函数
delete p;//调用析构、释放空间
Test *p1 = (Test*)operator new(sizeof(Test))
}
2、operator new
功能:
1)申请空间
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Create Test Object ."<<endl;
data = malloc(sizeof(int)*10);
}
~Test()
{
free data;
}
public:
Create_Test()
{
cout<<" Createf Test Object by operator new."<<endl;
}
private:
int *data;
};
void * operator new(size_t sz)
{
void * p = malloc(sz);
assert(*p != NULL);
return p;
}
void oprator delete(void *p)
{
delete p;
}
int main()
{
Test *p = (Test*)operator new(sizeof(Test));
p->Create_Test();
operator delete(p);
}
3、placement new
//必须先有空间
#include<iostream>
using namespace std;
void* operator new(size_t sz, int *ptr, int pos)//系统计算第一个参数大小
{
return &ptr[pos];
}
int main()
{
int ar[10] = {0};//出事化数组所有元素为0
new(ar,3) int(2);//ar维数组名,3为下标,2是要设置的值
new(ar) int(3);//ar为ar首地址,ar[0]等于ar,在这里是ar是定位设置ar[0]的值
for(int i=0; i<10; ++i)
{
cout<<ar[i]<<" ";
}
cout<<endl;
return 0;
}
输出:
3 0 0 2 0 0 0 0 0 0
4、set_new_halder
#include<iostream>
using namespace std;
void Out_Of_Memory()
{
cout<<"Out of Memory"<<endl;
exit(1);//没有回死循环
}
//回调函数
int main()
{
set_new_handler(Out_Of_Memory);//预先设置,事件发生了会调用
int *p = (int *)malloc(sizeof(int)*5);//如果空间开辟失败了会调动set_new_handler函数
/*if(p == NULL
{
cout<<"Out of Memory"<<endl;
exit(1);
}*/
cout<<"Memory Ok"<<endl;
}
以上便是new操作符的动态开辟空间三种发放和一种处理应急机制。加有注释说明,请仔细阅读。