07.2 关于 new(std::nothrow)

源码方面的信息就不详细讲述了,找找代码看看便知,简要说明下:
new(std::nothrow)顾名思义,即不抛出异常,当new一个对象失败时,默认设置该对象为NULL,这样可以方便的通过if(p == NULL)来判断new操作是否成功
普通的new操作,如果分配内存失败则会抛出异常,虽然后面一般也会写上if(p == NULL)但是实际上是自欺欺人,因为如果分配成功,p肯定不为NULL;而如果分配失败,则程序会抛出异常,if语句根本执行不到。

因此,建议在c++代码中,凡是涉及到new操作,都采用new(std::nothrow),然后if(p==NULL)的方式进行判断

按照这个方式,调用nothrow new的代码将可以使用统一的变量名字。比如:

#include <new>  
#include <iostream> // for std::cerr  
#include <cstdlib> // for std::exit()  
Task * ptask = new (std::nothrow) Task;  
if (!ptask)  
{  
std::cerr<<"allocation failure!";  
std::exit(1);  
}  
//... allocation succeeded; continue normally   

但是,你可以注意到你创建了你自己的nothrow_t对象来完成相同的效应:

#include <new>  
std::nothrow_t nt;  
Task * ptask = new (nt) Task; //user-defined argument  
if (!ptask)  
//...   
分配失败是非常普通的,它们通常在植入性和不支持异常的可移动的器件中发生更频繁。因此,应用程序开发者在这个环境中使用nothrow new来替代普通的new是非常安全的。

转载:https://blog.csdn.net/coloriy/article/details/50503570

猜你喜欢

转载自blog.csdn.net/weixin_41755681/article/details/80064269
今日推荐