noexcept
運算子 (C++11 起)
來自 cppreference.com
noexcept 運算子執行編譯時檢查,如果表示式宣告為不丟擲任何異常,則返回 true。
它可以在函式模板的 noexcept 說明符 中使用,以宣告該函式對某些型別丟擲異常,而對其他型別不丟擲異常。
目錄 |
[編輯] 語法
noexcept( expression ) |
|||||||||
返回型別為 bool 的 prvalue。如果 expression 的 潛在異常 集合為空(C++17 前)expression 被指定為 不丟擲(C++17 起),結果為 true,否則為 false。
expression 是一個 未求值運算元。
如果 expression 是一個 prvalue,則應用 臨時實體化。 |
(C++17 起) |
[編輯] 注意
即使 noexcept(expr) 為 true,對 expr 的求值仍可能由於遇到未定義行為而丟擲異常。
如果 expression 是類型別或其(可能是多維)陣列,臨時實體化要求解構函式是非刪除且可訪問的。 |
(C++17 起) |
[編輯] 關鍵詞
[編輯] 示例
執行此程式碼
#include <iostream> #include <utility> #include <vector> void may_throw(); void no_throw() noexcept; auto lmay_throw = []{}; auto lno_throw = []() noexcept {}; class T { public: ~T(){} // dtor prevents move ctor // copy ctor is noexcept }; class U { public: ~U(){} // dtor prevents move ctor // copy ctor is noexcept(false) std::vector<int> v; }; class V { public: std::vector<int> v; }; int main() { T t; U u; V v; std::cout << std::boolalpha << "may_throw() is noexcept(" << noexcept(may_throw()) << ")\n" "no_throw() is noexcept(" << noexcept(no_throw()) << ")\n" "lmay_throw() is noexcept(" << noexcept(lmay_throw()) << ")\n" "lno_throw() is noexcept(" << noexcept(lno_throw()) << ")\n" "~T() is noexcept(" << noexcept(std::declval<T>().~T()) << ")\n" // note: the following tests also require that ~T() is noexcept because // the expression within noexcept constructs and destroys a temporary "T(rvalue T) is noexcept(" << noexcept(T(std::declval<T>())) << ")\n" "T(lvalue T) is noexcept(" << noexcept(T(t)) << ")\n" "U(rvalue U) is noexcept(" << noexcept(U(std::declval<U>())) << ")\n" "U(lvalue U) is noexcept(" << noexcept(U(u)) << ")\n" "V(rvalue V) is noexcept(" << noexcept(V(std::declval<V>())) << ")\n" "V(lvalue V) is noexcept(" << noexcept(V(v)) << ")\n"; }
輸出
may_throw() is noexcept(false) no_throw() is noexcept(true) lmay_throw() is noexcept(false) lno_throw() is noexcept(true) ~T() is noexcept(true) T(rvalue T) is noexcept(true) T(lvalue T) is noexcept(true) U(rvalue U) is noexcept(false) U(lvalue U) is noexcept(false) V(rvalue V) is noexcept(true) V(lvalue V) is noexcept(false)
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
CWG 2722 | C++17 | 不清楚是否應用臨時實體化 如果 expression 是 prvalue |
它被應用 在這種情況下 |
CWG 2792 | C++11 | 要求 noexcept 運算子確定在遇到未定義行為時是否丟擲異常 在遇到未定義行為時是否可能丟擲異常 |
未要求 |
[編輯] 另請參閱
noexcept 說明符(C++11) |
指定函式是否可能丟擲異常 |
動態異常規範(C++17 前) | 指定函式丟擲哪些異常 (C++11 中已棄用) |