If a function is defined with a [[nodiscard]]
attribute or if it returns an object which is [[nodiscard]]
, its return
value is very important and should not be silently ignored.
Noncompliant code example
struct [[nodiscard]] ErrorInfo{ /* ... */};
ErrorInfo getStatus();
[[nodiscard]] int getInfo();
void f() {
getStatus(); // Noncompliant; we should read the returned struct which is "nodiscard"
getInfo(); // Noncompliant; we should read the return value of this "nodiscard" function
// ...
}
Compliant solution
struct[[nodiscard]] ErrorInfo{ /* ... */};
ErrorInfo getStatus();
[[nodiscard]] int getInfo();
void f() {
int status = getStatus(); // Compliant
if (getInfo() != 0) { /*...*/ } // Compliant
// ...
}
Exceptions
This rule will ignore return values that are not used, but are cast into void, since this is the standard-approved way to suppress this check.
[[nodiscard]] int getInfo();
void f() {
(void) getInfo(); // Compliant
// ...
}