c++ - 为什么 clang-tidy 建议在任何地方添加 [[nodiscard]] ?

标签 c++ clang clang-tidy nodiscard

我有一个 C++ 项目,其中 clang-tidy建议添加[[nodiscard]]到处。这是一个好习惯吗?我的理解是[[nodiscard]]仅当忽略返回值对程序可能是致命的时才应使用。我有一个对象 Car它有一个成员const unsigned int m_ID .如果 setter/getter unsigned int getID()[[nodiscard]] ? clang-tidy 建议如此。
编辑:
当然,我不想忽略 getter。但
我的观点是,如果每个返回值的函数都应该有 [[nodiscard]] ,然后属性 [[nodiscard]]反正是多余的。编译器可以简单地检查所有返回值的函数。

最佳答案

这个选项显然是 "modernize-use-nodiscard", so you can deactivate that if you prefer .
应该注意,此选项概​​述的规则不是 C++ 标准委员会自己在何时应用 [[nodiscard]] 时使用的规则。 . Those rules being :

It should be added where:

  • For existing API’s
    • not using the return value always is a “huge mistake” (e.g. always resulting in resource leak)
    • not using the return value is a source of trouble and easily can happen (not obvious that something is wrong)
  • For new API’s (not been in the C++ standard yet)
    • not using the return value is usually an error.

It should not be added when:

  • For existing API’s
    • not using the return value is a possible/common way of programming at least for some input
      • for example for realloc(), which acts like free when the new site[sic] is 0
    • not using the return value makes no sense but doesn’t hurt and is usually not an error (e.g., because programmers meant to ask for a state change).
    • it is a C function, because their declaration might not be under control of the C++ implementation

这就是为什么像 operator new 这样的函数是 [[nodiscard]] , 而像 optional::value 这样的函数不是。你的代码有一个小错误和你的代码从根本上被破坏是有区别的。 [[nodiscard]] ,就委员会而言,是为后者。
请注意,容器 empty方法是一种特殊情况。它们似乎符合“不使用 [[nodiscard]]”的模式,但因为 empty 的名称类似于 clear 的名称, 如果不使用 empty 的返回值, 你打算调用 clear 的可能性很大.
显然,这不能仅从声明中得知,因此 Clang-Tidy 无法实现所述规则。

关于c++ - 为什么 clang-tidy 建议在任何地方添加 [[nodiscard]] ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67059884/

相关文章:

c++ - 每次我启动新的VS项目 “Spectre-mitigated libraries are required for this project.”时出错

c++ - boost::sregex_iterator 编译错误

c++ - Xcode 9 开始在 C++ 中构建部分模板特化

c++ - clang-tidy 报告未知警告

c++ - Clang-tidy 文件 : How to list the checks in multiple lines

c++ - 在 C++ 类中将指针作为成员字段是不是很愚蠢?

c++ - LLVM异常处理错误

ios - clang 可以检测 iOS 中的 IBActionAttr 吗?

c++ - 避免指针算术,修复clang整齐的错误

c++ - 默认构造函数调用