在C++中也有和C语言的一样有专有的动态开辟空间操作符,C++的专有动态操作符是使用new操作符来开辟,配套的释放空间使用的是delete。但是初学C++的很多人只知道new操作符的简单使用,不知道new还有三种操作符,他们也有着不同的作用和使用方法,它们分别是new operator、operator new和placement new,还有一个在动态申请空间申请出错设置处理函数而不会使程序崩掉,下面我们来看看C++下面new操作符的这四个属性的具体实现:
功能: 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)) }功能: 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 0 0 2 0 0 0 0 0 0
以上便是new操作符的动态开辟空间三种发放和一种处理应急机制。加有注释说明,请仔细阅读。
