noexcept 运算符进行编译时检查,若表达式声明为不抛出任何异常则返回 true。

它可用于函数模板的 noexcept 说明符中,以声明函数将对某些类型抛出异常,但不对其他类型抛出。

语法

noexcept( 表达式 )

返回 bool 类型的纯右值

解释

noexcept 运算符不对 表达式 求值。


若 表达式 含有至少一个下列潜在求值的语言构造,则结果为 false


-
- 调用无不抛出异常说明的任何类型的函数,除非它是常量表达式
- throw 表达式
- 目标类型为引用类型,且转换需要运行时检查的 dynamic_cast 表达式
- 实参类型为多态类类型的 typeid 表达式

所有其他情况下结果是 true
(C++17 前)

若 表达式 的潜在异常集合为空则结果为 true,否则为 false
(C++17 起)

关键词

noexcept

示例

运行此代码

  1. #include <iostream>
  2. #include <utility>
  3. #include <vector>
  4.  
  5. void may_throw();
  6. void no_throw() noexcept;
  7. auto lmay_throw = []{};
  8. auto lno_throw = []() noexcept {};
  9. class T{
  10. public:
  11. ~T(){} // 析构函数妨碍了移动构造函数
  12. // 复制构造函数为 noexcept
  13. };
  14. class U{
  15. public:
  16. ~U(){} // 析构函数妨碍了移动构造函数
  17. // 复制构造函数为 noexcept(false)
  18. std::vector<int> v;
  19. };
  20. class V{
  21. public:
  22. std::vector<int> v;
  23. };
  24.  
  25. int main()
  26. {
  27. T t;
  28. U u;
  29. V v;
  30.  
  31. std::cout << std::boolalpha
  32. << "Is may_throw() noexcept? " << noexcept(may_throw()) << '\n'
  33. << "Is no_throw() noexcept? " << noexcept(no_throw()) << '\n'
  34. << "Is lmay_throw() noexcept? " << noexcept(lmay_throw()) << '\n'
  35. << "Is lno_throw() noexcept? " << noexcept(lno_throw()) << '\n'
  36. << "Is ~T() noexcept? " << noexcept(std::declval<T>().~T()) << '\n'
  37. // 注:以下各项测试也要求 ~T() 为 noexcept
  38. // 因为 noexccept 中的表达式构造并销毁了临时量
  39. << "Is T(rvalue T) noexcept? " << noexcept(T(std::declval<T>())) << '\n'
  40. << "Is T(lvalue T) noexcept? " << noexcept(T(t)) << '\n'
  41. << "Is U(rvalue U) noexcept? " << noexcept(U(std::declval<U>())) << '\n'
  42. << "Is U(lvalue U) noexcept? " << noexcept(U(u)) << '\n'
  43. << "Is V(rvalue V) noexcept? " << noexcept(V(std::declval<V>())) << '\n'
  44. << "Is V(lvalue V) noexcept? " << noexcept(V(v)) << '\n';
  45. }

输出:

  1. Is may_throw() noexcept? false
  2. Is no_throw() noexcept? true
  3. Is lmay_throw() noexcept? false
  4. Is lno_throw() noexcept? true
  5. Is ~T() noexcept? true
  6. Is T(rvalue T) noexcept? true
  7. Is T(lvalue T) noexcept? true
  8. Is U(rvalue U) noexcept? false
  9. Is U(lvalue U) noexcept? false
  10. Is V(rvalue V) noexcept? true
  11. Is V(lvalue V) noexcept? false