new (std::nothrow) 与 new

普通new一个异常的类型std::bad_alloc。这个是标准适应性态。
在早期C++的舞台上,这个性态和如今的很是不一样;new将返回0来指出一个失败,和malloc()很是类似。ios

    在内存不足时,new (std::nothrow)并不抛出异常,而是将指针置NULL安全

 在必定的环境下,返回一个NULL指针来表示一个失败依然是一个不错的选择。
C++标准委员会意识到这个问题,因此他们决定定义一个特别的new操做符版本,这个版本返回0表示失败。this

 一个nothow new语句和普通的new语句类似,除了它的变量将涉及到std::nothrow_t。Class std::nothrow_t在new将按照下面的方式来定义:spa

class nothrow_t // in namespace std
{}; //empty class指针

Operator nothrow new is declared like this:orm

//declarations from <new>
void *  operator new (size_t size, const std::nothrow_t &);
//array version
void *  operator new[] (size_t size, const std::nothrow_t &);对象

In addition, <new> defines a const global object of type nothrow_t:内存

extern const nothrow_t nothrow; //in namespace std开发

   按照这个方式,调用nothrow new的代码将能够使用统一的变量名字。好比:it

#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是很是安全的。

相关文章
相关标签/搜索