C++中nothrow的介绍及使用
在C中,使用malloc等分配內(nèi)存的函數(shù)時(shí),一定要檢查其返回值是否為”空指針”,并以此作為檢查內(nèi)存操作是否成功的依據(jù),這種Test-for-NULL代碼形式是一種良好的編程習(xí)慣,也是編寫可靠程序所必需的。
在C++中new在申請(qǐng)內(nèi)存失敗時(shí)默認(rèn)會(huì)拋出一個(gè)std::bad_alloc 異常。如果出現(xiàn)這個(gè)異常,那就意味著內(nèi)存耗盡,或者有其它原因?qū)е聝?nèi)存分配失敗。所以,按照C++標(biāo)準(zhǔn),如果想檢查new是否成功,則應(yīng)該通過try catch捕捉異常。但有些編譯器不支持try catch。C++標(biāo)準(zhǔn)化委員會(huì)不想遺棄這些Test-for-NULL的代碼,所以他們提供了operator new的另一種可選形式---- nothrow,用以提供傳統(tǒng)的Failure-yields-NULL行為。
當(dāng)使用new申請(qǐng)一塊內(nèi)存失敗時(shí),拋出異常std::bad_alloc是C++標(biāo)準(zhǔn)中規(guī)定的標(biāo)準(zhǔn)行為,所以使用try { p = new int[size];} catch(std::bad_alloc) { … } 的處理方式。
struct nothrow_t {// placement new tag type to suppress exceptions
};extern const nothrow_t nothrow; // constant for placement new tag
其中,nothrow_t通常是一個(gè)空結(jié)構(gòu),其唯一目的是提供編譯器一個(gè)可根據(jù)重載規(guī)則識(shí)別具體調(diào)用的類型。用戶一般簡單地使用"new(std::nothrow) 類型"(nothrow是一個(gè)nothrow_t類型的常量)來調(diào)用這個(gè)placement new操作符。它與標(biāo)準(zhǔn)new的區(qū)別是,new在分配內(nèi)存失敗時(shí)會(huì)拋出異常,而"new(std::nothrow)"在分配內(nèi)存失敗時(shí)會(huì)返回一個(gè)空指針。
new operator分配內(nèi)存失敗后,缺省的行為不是返回NULL,而是拋出異常std::bad_alloc。所以判斷返回值是否為NULL沒有任何意義。
? std::nothrow: This constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure, but return a null pointer instead.
By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as argument for new, it returns a null pointer instead.
This constant (nothrow) is just a value of type nothrow_t, with the only purpose of triggering an overloaded version of the function operator new (or operatornew[]) that takes an argument of this type.
以下是測試代碼:
#include "nothrow.hpp"
#include <iostream>
#include <new> // std::nothrow// reference: http://www.cplusplus.com/reference/new/nothrow/
int test_nothrow1()
{std::cout << "Attempting to allocate 1 MiB...";char* p = new (std::nothrow) char[1048576];if (p == 0)std::cout << "Failed!\n";else {std::cout << "Succeeded!\n";delete[] p;}return 0;
}// reference: http://en.cppreference.com/w/cpp/memory/new/nothrow
int test_nothrow2()
{try {while (true) {new int[100000000ul]; // throwing overload}}catch (const std::bad_alloc& e) {std::cout << e.what() << '\n';}while (true) {int* p = new(std::nothrow) int[100000000ul]; // non-throwing overloadif (p == nullptr) {std::cout << "Allocation returned nullptr\n";break;}}return 0;
}
GitHub:
https://github.com/fengbingchun/Messy_Test
總結(jié)
以上是生活随笔為你收集整理的C++中nothrow的介绍及使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++/C++11中std::set用法
- 下一篇: Caffe源码中Solver文件分析