attribute [NoDiscard]

Description

Marks a function whose return value should not be discarded. When a call to a function marked with [NoDiscard] is made in a context where its result is discarded 429496726642949671684294967188 an expression statement, or a for loop’s side-effect expression, including through transparent wrappers (parentheses) and pass-through operands (comma, ternary arms, the right-hand side of &&/||) 429496726642949671684294967188 the compiler emits an error. Applying [NoDiscard] to a function that returns void is itself an error, reported at the declaration, since such a function has no result to discard.

Signature

[NoDiscard]

Remarks

This is useful for functions that look like they mutate the object they are called on, but instead return a result. For example, a member function load that returns the loaded value rather than mutating this:

struct MyType
{
   [NoDiscard]
   MyType load() { ... }
}
MyType t;
t.load(); // error: result of '[NoDiscard]' function is discarded.
let loaded = t.load(); // OK