1. plain new 普通new
- void*operator new(std::size_t)throw(std::bad_alloc);
- void operator delete( void *) throw();
- char *getMemory(unsigned long size)
- { char * p = new char[size];
- return p; }
- void main(void )
- { try{
- char * p = getMemory(1000000);//可能发生异常
- // ...
- delete [ ] p;
- }
- catch(const std::bad_alloc & ex)
- { cout < <ex.what(); }
- }
- void*operator new(std::size_t,const std::nothrow_t & )throw();
- void operator delete( void *) throw();
该函数的第2形参是 struct nothrow_t { };它是个全局常对象 const nothrow_t nothrow; 用来作为 new 运算符的标志,以区别前一个new.
3.placement new 放置new
- >void*operator new(std::size_t ,void *);
- void operator delete( void * ,void *);
- # include <new>
- # include <iostream>
- void main()
- { using namespace std;
- char * p = new(nothrow) char [4];
- if (p == NULL)
- { cout < <“allocte failed” < <endl; exit( -1 ); }
- // ...
- long * q = new(p)long(1000);
- delete [ ]p; //只释放 p,不要用q释放。
- }
该运算符的作用是:只要第一次分配成功,不再担心分配失败。
提示3:placement new 的主要用途:反复使用一块较大的动态分配成功的内存来构造不同类型的对象或者他们的数组。这样可以避免申请失败的徒劳,又可以避免使用后的释放。
- # include <new>
- # include <iostream>
- void main()
- { using namespace std;
- char * p = new(nothrow) char [100];
- if (p == NULL)
- { cout < <“allocte failed” < <endl; exit( -1 ); }
- long * q1 = new(p)long(100);
- // 使用q1 ...
- int * q2 = new(p) int[100/sizeof(int) ];
- // 使用q2 ...
- ADT * q3 = new(p) ADT[100/sizeof(ADT) ];
- // 使用q3 然后释放对象 ...
- delete [ ]p; //只释放空间,不再析构对象。
- }
- # include <new>
- # include <iostream>
- void main()
- { using namespace std;
- char * p = new(nothrow) char [sizeof(ADT)+2];
- if (p == NULL)
- { cout < <“allocte failed” < <endl; exit( -1 ); }
- // ...
- ADT * q = new(p) ADT;
- // ...
- // delete q; // 错误
- q-> ADT::~ADT(); //显式调用析构函数,仅释放对象
- delete [ ]p; //最后,再用原指针来释放内存.
- }