gpt4 book ai didi

c++ - 我应该声明所有不抛出 noexcept 的成员/函数吗?

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

CppCoreGuidelines 之一是 E.12:因为抛出是不可能的或 Not Acceptable 而退出函数时使用 noexcept。这是否意味着我应该在不抛出异常并且不调用抛出的其他方法/函数的每个成员和函数上声明 noexcept ?我知道总是尽可能多地声明 const 是一个很好的搪塞,我在不同的项目中看到了很多 const 方法,但是我没有看到 noexcept 使用那么多。

最佳答案

Should I declare all members/function that doesn't throw noexcept?

这个答案不会试图回答这是否是一个好的做法(自以为是),但请注意,在进行安全关键的 C++ 开发时,这种做法很常见,而且更严格的 C++ 准则通常要求 所有非抛出函数的声明都包含 noexcept specifier .

AUTOSAR C++14 指南

例如,Guidelines for the use of the C++14 language in critical and safety-related systems 中的规则 A15-4-4来自 AUTOSAR(一个非官方的,但来自 MISRA C++:2008 的行业事实上的继任者)涵盖了这种做法以及一个基本原理:

Rule A15-4-4 (required, implementation, automated)

A declaration of non-throwing function shall contain noexcept specification.

Rationale

Noexcept specification is a method for a programmer to inform thecompiler whether or not a function should throw exceptions. Thecompiler can use this information to enable certain optimizations onnon-throwing functions as well as enable the noexcept operator, whichcan check at compile time if a particular expression is declared tothrow any exceptions.

Noexcept specification is also a method to inform other programmersthat a function does not throw any exceptions.

A non-throwing function needs to declare noexcept specifier.A function that may or may not throw exceptions depending on a templateargument, needs to explicitly specify its behavior usingnoexcept() specifier.

Note that it is assumed that a function which does not containexplicit noexcept specification throws exceptions, similarly tofunctions that declare noexcept(false) specifier.

required 标签应用于规则,如果要声称代码库符合指南要求,则需要满足这些规则:

5.1.2 Rule classification according to obligation level

required: these are mandatory requirements placed on the code. C++ code that is claimed to conform to AUTOSAR C++14 shall comply withevery “Required” rule. Formal deviations must be raised where this isnot the case.

当然,由特定公司/供应商决定是否以及如何遵守 AUTOSAR C++14,但通常 OEM要求符合特定的条件标准,例如对于 C++ MISRA C++:2008 或 AUTOSAR C++14,与特定规则的偏差通常需要经过正式的偏差流程。

automated 标签应用于可以通过静态分析轻松自动执行的规则。

关于c++ - 我应该声明所有不抛出 noexcept 的成员/函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62713967/

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