[转] C++ 中的三种new

    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值