new (std::nothrow) 與 new


普通new一個異常的類型std::bad_alloc。這個是標准適應性態。
在早期C++的舞台上,這個性態和現在的非常不同;new將返回0來指出一個失敗,和malloc()非常相似。

    在內存不足時,new (std::nothrow)並不拋出異常,而是將指針置NULL

 在一定的環境下,返回一個NULL指針來表示一個失敗依然是一個不錯的選擇。
C++標准委員會意識到這個問題,所以他們決定定義一個特別的new操作符版本,這個版本返回0表示失敗。

 一個nothow new語句和普通的new語句相似,除了它的變量將涉及到std::nothrow_t。Class std::nothrow_t在new將按照下面的方式來定義:

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

Operator nothrow new is declared like this:

//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的代碼將可以使用統一的變量名字。比如:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM