C++中的 new 有3中使用方式,它们是: plain new 、 nothrow new 和 placement new 。这3种形式极大地扩展了内存分配的灵活性。
1. plain new
从字面上看,这就是普通的 new ,也是我们平时使用的 new ,这里就不多说。
2. nothrow new
nothrow new 就是部抛出异常的 new ,在失败的时候返回 NULL;所以使用时不需要设置异常处理,而普通的 new 在使用失败时是需要设置异常处理模块的。
使用格式如下:
view plaincopy to clipboardprint?
unsigned char *p = new(nothrow) unsigned char[length];
if(p == NULL) cout<<"allocate failed!"<<endl;
// ...
delete []p;
unsigned char *p = new(nothrow) unsigned char[length];
if(p == NULL) cout<<"allocate failed!"<<endl;
// ...
delete []p;
3.placement new
这种 new 形式允许在一块已经分配成功的内存上重新构造对象或者对象数组。使用时不必担心失败,因为它根本就不会分配内存;使用它构造起来的对象,要显示的调用它们的析构函数,而不能使用 delete 。
使用格式如下:
view plaincopy to clipboardprint?
#include <new>
#include <iostream>
void main()
{
using namespace std;
char *p = new(nothrow) char[4]; // nothrow new
if(p == NULL)
{
cout<<"allocate failed!"<<endl;
exit(-1);
}
//...
long *q = new(p) long(1000); // placement new
//...
delete []p;
}
#include <new>
#include <iostream>
void main()
{
using namespace std;
char *p = new(nothrow) char[4]; // nothrow new
if(p == NULL)
{
cout<<"allocate failed!"<<endl;
exit(-1);
}
//...
long *q = new(p) long(1000); // placement new
//...
delete []p;
}
最后说明一下,在使用后面两种方法时,记得要加 #include <new>.
这里再添加一个new使用的解说。
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/vangoals/archive/2009/06/08/4252833.aspx