Search⌘ K
AI Features

Where Can It Be Used?

Explore how the [[nodiscard]] attribute in C++17 enhances code safety by enforcing the checking of returned values, particularly for error codes, factory functions, and non-trivial types. Understand practical use cases to avoid overlooked errors and improve program reliability.

Attributes are a standardised way of annotating the code. They are optional, but they might help the compiler to optimize code, detect possible errors or just clearly express the programmer’s intentions.

Here are a few places where [[nodiscard]] can be potentially handy:

Errors

One crucial use case for [[nodiscard]] are error codes.

How many times have you forgotten to check a returned error code from a function? (Crucial if you don’t rely on exceptions).

Here’s some code:

C++
enum class [[nodiscard]] ErrorCode {
OK,
Fatal,
System,
FileIssue
};

And if we have several ...