The [[nodiscard]]
attribute can be applied to functions and custom types to encourage users to handle the return value. When a [[nodiscard]]
function or object is called and its return value is discarded, the compiler will generate a warning.
To use [[nodiscard]]
with your custom types, you can apply the attribute to the type declaration itself or to specific member functions that should not have their return values discarded.
Here's an example of using [[nodiscard]]
with a custom type:
#include <iostream>
class [[nodiscard]] Result {
public:
bool success;
int value;
Result(bool s, int v) : success(s), value(v) {}
};
Result divide(int a, int b) {
if (b == 0) {
return {false, 0};
}
return {true, a / b};
}
int main() {
// Warning: ignoring return value
divide(10, 2);
Result res = divide(10, 0);
if (!res.success) {
std::cout << "Division failed\n";
} else {
std::cout << "Result: " << res.value << '\n';
}
}
Division failed
Warning: discarding return value of function with [[nodiscard]] attribute
In this example, the Result
class is marked with [[nodiscard]]
, indicating that instances of this type should not have their return values discarded. The divide
function returns a Result
object, and if the return value is not handled (as in the first call to divide
in main
), the compiler will generate a warning.
You can also apply [[nodiscard]]
to specific member functions instead of the entire type:
class Result {
public:
[[nodiscard]] bool success() const {
return m_success; }
private:
bool m_success;
};
By using [[nodiscard]]
with your custom types, you can enforce better code practices and encourage users to handle important return values explicitly.
Answers to questions are automatically generated and may not have been reviewed.
A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more