C++ [[nodiscard]]


Example

C++17

The [[nodiscard]] attribute can be used to indicate that the return value of a function shouldn't be ignored when you do a function call. If the return value is ignored, the compiler should give a warning on this. The attribute can be added to:

  • A function definition
  • A type

Adding the attribute to a type has the same behaviour as adding the attribute to every single function which returns this type.

template<typename Function>
[[nodiscard]] Finally<std::decay_t<Function>> onExit(Function &&f);

void f(int &i) {
    assert(i == 0);                    // Just to make comments clear!
    ++i;                               // i == 1
    auto exit1 = onExit([&i]{ --i; }); // Reduce by 1 on exiting f()
    ++i;                               // i == 2
    onExit([&i]{ --i; });              // BUG: Reducing by 1 directly
                                       //      Compiler warning expected
    std::cout << i << std::end;        // Expected: 2, Real: 1
}

See the proposal for more detailed examples on how [[nodiscard]] can be used.

Note: The implementation details of Finally/onExit are omitted in the example, see Finally/ScopeExit.