从 [[nodiscard]] 中排除函数的返回值

Hao*_*hun 5 c++ c++17 nodiscard

我想将一个类标记为 nodiscard,但将某个函数的返回值排除在 nodiscard 要求之外。这是我的目标:

enum class [[nodiscard]] Result {
  OK1,
  OK2,
  ERROR,
};

[[ok-to-discard]] // This attribute is made up to illustrate my need.
Result doSomethingThatCannotFail() {
  // The function can return OK1 or OK2, but the caller may or may not care.
  // The function cannot return ERROR.
  // Therefore, it's OK to discard this particular Result return value,
  // even though in general Result should not be ignored.
}
Run Code Online (Sandbox Code Playgroud)

我不认为在每个调用站点添加 ok-to-discard 是一个好主意(这由 如何故意丢弃 [[nodiscard]] 返回值? 涵盖):

  • 有很多调用点。最好避免在任何地方添加 ok-todiscard。
  • 也许有一天我会改变这个功能,就不再可以丢弃了。最好将 ok-to-discard 指令与该函数一起保留,以便我可以在发生这种情况时删除它(并获得编译器警告/错误)。