Using [[nodiscard]] with custom types

How can I use the [[nodiscard]] attribute with my own custom types?

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.

Odds and Ends: 10 Useful Techniques

A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to use std::vector vs std::array
When should I use std::vector and when should I use std::array in C++?
Measuring execution time with
How can I measure the execution time of a function using the library?
Choosing the right random number distribution
How do I choose the appropriate random number distribution for my use case?
Creating a custom ClangFormat style
How can I create a custom ClangFormat style for my C++ project?
Integrating static analysis tools into your workflow
How can I integrate static analysis tools like Cppcheck into my C++ development workflow?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant