In a project using C++20, CLion suggested me to add [[nodiscard]]
to my const class method definitions, e.g.,
class Test {
public:
[[nodiscard]] int f(int a, int b) const {
return a + b;
}
}
The explanation is
Adds [[nodiscard]] attributes (introduced in C++17) to member functions in order to highlight at compile time which return values should not be ignored.
and I also checked cppreference.com:
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. ... Appears in a function declaration, enumeration declaration, or class declaration.
If, from a discarded-value expression other than a cast to void,
- a function declared nodiscard is called, or
- a function returning an enumeration or class declared nodiscard by value is called, or
- a constructor declared nodiscard is called by explicit type conversion or static_cast, or
- an object of an enumeration or class type declared nodiscard is initialized by explicit type conversion or static_cast,
the compiler is encouraged to issue a warning.
I honestly don't really understand why this annotation is needed in this location. Why would the compiler ignore my return values if the caller processes them further? Is there an intuitive explanation of what it tells the compiler exactly and why it's needed?