noexcept 运算符 (C++11 起)

来自cppreference.com
< cpp‎ | language

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

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

目录

[编辑] 语法

noexcept( expression )

返回 bool 类型的纯右值

[编辑] 解释

noexcept 运算符不对 expression 求值。

expression 含有至少一个下列潜在求值的构造则结果为 false

所有其他情况下结果是 true

(C++17 前)

expression潜在异常集合为空则结果为 true ,否则为 false

(C++17 起)

[编辑] 关键词

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'
           // note: the following tests also require that ~T() is noexcept because
           // the expression within noexcept constructs and destroys a temporary
           << "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) [编辑]
异常规定 指定函数所抛出的异常 (弃用) [编辑]