5

我想将一个类标记为 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.
}

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

  • 有许多呼叫站点。避免到处添加 ok-to-discard 会很好。
  • 说不定哪天我换个功能,丢了就不行了。最好将 ok-to-discard 指令与函数一起保留,以便在发生这种情况时将其删除(并获得编译器警告/错误)。
4

0 回答 0