CppDS.com

C++ 98 11 14 17 20 手册

noexcept 运算符 (C++11 起)

来自cppreference.com
< cpp‎ | language

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

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

语法

noexcept( 表达式 )

返回 bool 类型的纯右值

解释

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

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

关键词

noexcept

示例

#include <iostream>
#include <utility>
#include <vector>
 
void may_throw();
void no_throw() noexcept;
auto lmay_throw = []{};
auto lno_throw = []() noexcept {};
class T{
public:
  ~T(){} // 析构函数妨碍了移动构造函数
         // 复制构造函数为 noexcept
};
class U{
public:
  ~U(){} // 析构函数妨碍了移动构造函数
         // 复制构造函数为 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
           << "Is may_throw() noexcept? " << noexcept(may_throw()) << '\n'
           << "Is no_throw() noexcept? " << noexcept(no_throw()) << '\n'
           << "Is lmay_throw() noexcept? " << noexcept(lmay_throw()) << '\n'
           << "Is lno_throw() noexcept? " << noexcept(lno_throw()) << '\n'
           << "Is ~T() noexcept? " << noexcept(std::declval<T>().~T()) << '\n'
           // 注:以下各项测试也要求 ~T() 为 noexcept
           // 因为 noexccept 中的表达式构造并销毁了临时量
           << "Is T(rvalue T) noexcept? " << noexcept(T(std::declval<T>())) << '\n'
           << "Is T(lvalue T) noexcept? " << noexcept(T(t)) << '\n'
           << "Is U(rvalue U) noexcept? " << noexcept(U(std::declval<U>())) << '\n'
           << "Is U(lvalue U) noexcept? " << noexcept(U(u)) << '\n'  
           << "Is V(rvalue V) noexcept? " << noexcept(V(std::declval<V>())) << '\n'
           << "Is V(lvalue V) noexcept? " << noexcept(V(v)) << '\n';  
}

输出:

Is may_throw() noexcept? false
Is no_throw() noexcept? true
Is lmay_throw() noexcept? false
Is lno_throw() noexcept? true
Is ~T() noexcept? true
Is T(rvalue T) noexcept? true
Is T(lvalue T) noexcept? true
Is U(rvalue U) noexcept? false
Is U(lvalue U) noexcept? false
Is V(rvalue V) noexcept? true
Is V(lvalue V) noexcept? false

参阅

noexcept 说明符(C++11) 要求函数不抛出任何异常
动态异常说明(C++17 前) 指定函数所抛出的异常 (C++11 中弃用)
关闭