noexcept
运算符进行编译时检查,若表达式声明为不抛出任何异常则返回 true。
它可用于函数模板的 noexcept 说明符中,以声明函数将对某些类型抛出异常,但不对其他类型抛出。
语法
noexcept( 表达式 ) | ||
返回 bool 类型的纯右值。
解释
noexcept
运算符不对 表达式 求值。
若 表达式 含有至少一个下列潜在求值的语言构造,则结果为 false :- - 调用无不抛出异常说明的任何类型的函数,除非它是常量表达式。 - throw 表达式。- 目标类型为引用类型,且转换需要运行时检查的 dynamic_cast 表达式- 实参类型为多态类类型的 typeid 表达式所有其他情况下结果是 true 。 | (C++17 前) |
若 表达式 的潜在异常集合为空则结果为 true ,否则为 false 。 | (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(){} // 析构函数妨碍了移动构造函数
- // 复制构造函数为 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
当前内容版权归 cppreference 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cppreference .