c++c++17nodiscard

Is nodiscard necessary on operators?


Is the [[nodiscard]] attribute necessary on operators? Or is it safe to assume the compiler will emit a warning like it does for most suspiciously discarded things?

E.g. an overloaded operator+, should one apply the attribute? What about special operators like function-cast operators or new operators? When is it pedantic?


Solution

  • Let me cite the following paper by N.Josuttis: "[[nodiscard]] in the library" (with some omissions, see the full paper):

    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.