运营商是否需要 nodiscard ?

Is nodiscard necessary on operators?

运算符是否需要 [[nodiscard]] 属性?或者假设编译器会像对大多数可疑丢弃的东西一样发出警告是否安全?

例如一个超载的 operator+,是否应该应用该属性?像函数转换运算符或新运算符这样的特殊运算符呢?什么时候迂腐了?

永远不需要 添加 [[nodiscard]] 属性。来自 cppreference:

If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.

注意最后一部分:“...鼓励编译器发出警告。”就标准而言,不能保证实际上会有警告。这是实施质量问题。如果您的编译器确实发出警告(阅读文档)并且您将此类警告视为错误,那么 [[nodiscard]] 可能会有很大用处。

在运算符上使用属性是迂腐的,因为丢弃 return 只是潜在的错误。我只会在调用运算符时使用它并且丢弃结果始终是逻辑错误。许多运算符仅使用 return 值来启用链接,而 [[nodiscard]] 宁愿成为此类运算符的烦恼。在某些情况下,决定不是那么明显,您选择什么是意见和风格的问题。

让我引用以下 N.Josuttis 的论文:“[[nodiscard]] in the library”(有一些遗漏,请参阅全文):

C++17 introduced the [[nodiscard]] attribute. The question is, where to apply it now in the standard library. It should be added where:

  • 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).

It should not be added when:

  • not using the return value is a possible/common way of programming at least for some input,
  • not using the return value makes no sense but doesn’t hurt and is usually not an error.

So, [[nodiscard]] should not signal bad code if this

  • can be useful not to use the return value,
  • is common not to use the return value,
  • doesn’t hurt and probably no state change was meant that doesn’t happen.

Is nodiscard necessary on operators?

没有。 nodiscard 和其他属性是可选的。

Or is it safe to assume the compiler will emit a warning like it does for most suspiciously discarded things?

除非程序格式错误,否则不能保证语言中的任何警告。

我也不会在没有 nodiscard 的情况下假设警告,因为在很多情况下,操作结果是有意丢弃的。一个常见的例子:

a = b;  // result of assignment was discarded

事实上,如果所有丢弃的结果都导致警告,那么 nodiscard 属性就没有任何意义了。