gpt4 book ai didi

c++ - 为什么编译器无法检测到 'noexcept'使用不匹配?

转载 作者:行者123 更新时间:2023-12-01 14:57:58 25 4
gpt4 key购买 nike

以下是一些代码,其中编译器部分检测了方法声明(即使用'noexcept'说明符)与方法实现之间的不匹配。

编译器报告方法“bazExcept()”的警告,但未报告“baz()”的任何内容。但是,我期望在这两种情况下都发出警告,因为“bazSub()”可能会引发异常,而“baz()”明确指出不会引发异常。

是正在进行中的工作(即以后的编译器版本会捕获这种情况)还是我对'noexcept'用法误解了?

// Tested with C++11 & C++17
// Tested with msvc 19, gcc 9 & clang 9
// Tested using https://godbolt.org/

// Specifier 'noexcept(false)' (same as no specifier) i.e. may throw exceptions.
void bar() noexcept(false) {}

// No specifier 'noexcept' means 'noexcept(false)' i.e. may throw exceptions.
void bazSub() { throw 42; }

// Specifier 'noexcept' means 'noexcept(true)' i.e. do not throw exceptions.
// Note: Compilers do not detect the problem i.e. bazSub may throw exception.
void baz() noexcept { bazSub(); }

// Specifier 'noexcept' means 'noexcept(true)' i.e. must not throw exceptions.
// Note: Compilers generate a warning.
void bazExcept() noexcept { throw 42; }

int main() {return 1;}

谢谢你的帮助。

最佳答案

Why compilers fail to detect a 'noexcept' usage mismatch?



因为它们不是必需的。编译器按照标准运行。

C++ draft in except#spec-5:

Whenever an exception is thrown and the search for a handler encounters the outermost block of a function with a non-throwing exception specification, the function std​::​terminate is called.



其次是重要说明:

An implementation is not permitted to reject an expression merely because, when executed, it throws or might throw an exception from a function with a non-throwing exception specification.



不允许编译器拒绝 noexcept函数的抛出,而仅调用 noexcept抛出 std::terminate函数。

关于c++ - 为什么编译器无法检测到 'noexcept'使用不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60548807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com