c++ - 是否有自动 noexcept 说明符?

标签 c++ c++11 c++14 noexcept

我听说 noexcept 关键字更像是“它永远不应该抛出异常”而不是“它不会”。

如果我不确定是否抛出异常,我认为使用 noexcept 关键字不是很好,但是 noexcept 关键字有时与性能有关就像在移动构造函数中一样。

所以我尝试使用 noexcept 限定符,但如果它在定义中有多个语句并且它变成一种复制和粘贴的东西,它会变得更加困难。

template <class T>
void f(T&& t)
    noexcept(noexcept(statement_1) &&
             noexcept(statement_2) &&
             noexcept(statement_3) &&
             noexcept(statement_4) &&
             noexcept(statement_5))
{
    statement_1;
    statement_2;
    statement_3;
    statement_4;
    statement_5;
}

我认为编译器可以判断函数的定义是否由非抛出语句组成,因此如果有像 noexcept(auto) 这样的表达式,使用 noexcept 会更容易,不过好像标准里没有这样的东西。

有什么方法可以简化 noexcept 表达式?

最佳答案

目前没有。然而,有一个关于该主题的提案,它提出了 noexcept(auto) 语法:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4473 根据 Botond Ballo 的“旅行报告:2015 年 5 月在 Lenexa 举行的 C++ 标准 session ”https://botondballo.wordpress.com/2015/06/05/trip-report-c-standards-meeting-in-lenexa-may-2015/,该提案的状态是“需要进一步工作”。

Further Work. The proposal’s direction is promising, but it is either not fleshed out well enough, or there are specific concerns with one or more design points. The author is encouraged to come back with a modified proposal that is more fleshed out and/or addresses the stated concerns.

...

noexcept(auto), which basically means “deduce the noexcept-ness of this function from the noexcept-ness of the functions it calls. Like return type deduction, this requires the body of the function being available in each translation unit that uses the function. It was brought up that, together with the proposal for making exception specifications part of the type system, this would mean that modifying the function’s body could change the function’s type (again similarly to return type deduction), but people weren’t overly concerned about that.

关于c++ - 是否有自动 noexcept 说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30456801/

相关文章:

c++ - vector 元素如何在 vector std::move 之后保留其原始地址?

c++ - 类 C 结构中自动字段重新排序的方法

c++ - Const 限定符和前向引用

c++ - boost 池 malloc() 和 free() 编译器错误

打开文件时出现 C++ 错误

c++ - 可变模板构造函数和移动构造函数

c++ - 具有智能指针附加继承对象的深拷贝

c++ - 缓存函数结果,包括 maybe void

c++ - int min 的定点实现

c++ - 在 C++ 中调用函数是不明确的。候选函数是原型(prototype)和函数本身