C++17 introduced [[nodiscard]] attribute. When you declare a function [[nodiscard]], you indicate that its
return value should not be ignored. This can help prevent bugs related to:
- Memory leak, in case the function returns a pointer to unmanaged memory
- Performance, in case the discarded value is costly to construct
- Security, in case the return value indicates an error condition that needs to be taken into account
If the return value is ignored, the compiler is encouraged to issue a warning. Also, our analyzer will raise an issue, see S5277.
Note that you can declare an enumeration or class nodiscard. In that case, the compiler will warn if the ignored value is coming from
a function that returns a nodiscard enumeration or class by value.
This rule will suggest adding the [[nodiscard]] attribute to functions with no side effects that return a value.
Noncompliant code example
struct A {
std::string name;
std::string& getName() { return name;} // Noncompliant
std::string const& getName() const {return name;} // Noncompliant
};
int sum(int x, int y) { // Noncompliant
return x + y;
}
Compliant solution
struct A {
std::string name;
[[nodiscard]] std::string& getName() { return name;} // Compliant
[[nodiscard]] std::string const& getName() const {return name;} // Compliant
};
[[nodiscard]] int sum(int x, int y) { // Compliant
return x + y;
}