Search code examples
c++c++20nodiscard

Why is the C++ standard library Container function empty() marked as [[nodiscard]]?


It seems like empty() is the only function that has been marked as nodiscard.

Other similar functions like size() have not.

Why is that?


Solution

  • First, I would expect that more functions will be marked [[nodiscard]] in the future.

    However, empty is traditionally a point of confusion for new users. They think that it's a verb, and that it will remove all the elements of a container (the correct call here is clear).

    So marking empty as [[nodiscard]] catches all the places where people call it expecting it to do something to the container (instead of just returning size() == 0)