c++clangclang-tidynodiscard

Why clang-tidy suggests to add [[nodiscard]] everywhere?


I have a C++ project where clang-tidy is suggesting to add [[nodiscard]] everywhere. Is this a good practice ? The understanding I have is that [[nodiscard]] should be used only when ignoring the return value could be fatal for program. I have an object Car and it has a member const unsigned int m_ID. Should the getter unsigned int getID() have [[nodiscard]] ? clang-tidy suggests so.

EDIT:

Of course, I do not want to ignore a getter. BUT
My point is if every function that returns something should have a [[nodiscard]], then the attribute [[nodiscard]] is anyway redundant. Compiler can simply check all functions that return something.


Solution

  • The modernize-use-nodiscard checker was a checker I added to clang-tidy. I wanted my team to use [[nodiscard]] liberally to catch cases where people were accidentally using a function called empty() when they meant to use clear().

    Because developers were coding like:

    list.empty()

    the presence of [[nodiscard]] on empty() forced the catching of such bugs. Once you start down this road you begin to see other places where people make mistakes, especially in a scenario where an api gets changed and now it returns something that should be handled.

    Anything that can help a compiler to catch unintentional behavior is valuable as it left shifts bugs.