std::nothrow
來自 cppreference.com
定義於標頭檔案 <new> |
||
(1) | ||
struct nothrow_t {}; |
(C++11 前) | |
struct nothrow_t { explicit nothrow_t() = default; }; |
(C++11 起) | |
extern const std::nothrow_t nothrow; |
(2) | |
std::nothrow_t
是一個空的類型別,用於區分丟擲異常和不丟擲異常的分配函式的過載。std::nothrow
是它的一個常量。
[編輯] 示例
執行此程式碼
#include <iostream> #include <new> int main() { 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 overload if (p == nullptr) { std::cout << "Allocation returned nullptr\n"; break; } } }
輸出
std::bad_alloc Allocation returned nullptr
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2510 | C++11 | 預設建構函式不是 explicit 的,可能導致歧義 | 改為 explicit |
[編輯] 參見
分配函式 (函式) |