noexcept specifier (C++11 起)

来自cppreference.com
< cpp‎ | language

 
 
C++语言
表达式
替代表示
字面量
布尔型 - 整型 - 浮点型
字符型 - 字符串 - nullptr (C++11)
用户定义 (C++11)
Utilities
属性 (C++11)
Types
typedef声明
类型别名声明 (C++11)
Casts
隐式类型转换 - 显示类型转换
static_cast - dynamic_cast
const_cast - reinterpret_cast
内存分配
类特有的函数属性
explicit (C++11)
static
静态成员函数
模板
杂项
 

Specifies whether a function will throw exceptions or not.

目录

[编辑] 语法

noexcept (1)
noexcept(expression) (2)

[编辑] 解释

If the value of the constant expression is true, the function is declared to not throw any exceptions. noexcept without a constant expression is equivalent to noexcept(true).

One of the uses of the constant expression is (along with the NJ运营商) to define templated functions that declare noexcept for some types but not others.

Note that a noexcept specification on a function is not a compile-time check; it is merely a method for a programmer to inform the compiler whether or not a function should throw exceptions. The compiler can use this information to enable certain optimizations on non-throwing functions as well as enable the NJ运营商, which can check at compile time if a particular expression is declared to throw any exceptions. For example, containers such as std::vector will move their elements if the elements' move constructor is noexcept, and copy otherwise.

If a function marked noexcept allows an uncaught exception to escape at runtime, std::terminate is called immediately.

[编辑] Deprecates

noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().

[编辑] 关键字

noexcept

[编辑] 示例

// whether foo is declared noexcept depends on if the expression
// T() will throw any exceptions
template <class T>
  void foo() noexcept(noexcept(T())) {}
void bar() noexcept(true) {}
void baz() noexcept { throw 42; }  // noexcept is the same as noexcept(true)
 
int main() 
{
    foo<int>();  // noexcept(noexcept(int())) => noexcept(true), so this is fine
 
    bar();  // fine
    baz();  // compiles, but at runtime this calls std::terminate
}


[编辑] 另请参阅

noexcept运营商 determines if an expression throws any exceptions (C++11 起) [edit]
异常规范
指定什么异常被抛出的功能(已弃用)
原文:
specifies what exceptions are thrown by a function (已弃用)
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里
[edit]
扔表达
错误信号和控制权转移给错误处理程序
原文:
signals an error and transfers control to error handler
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里
[edit]
获得一个右值引用的举动构造方法不抛出
原文:
obtains an rvalue reference if the move constructor does not throw
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里

(函数模板) [edit]