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

相關文章
相關標籤/搜索