Hacker News new | past | comments | ask | show | jobs | submit login

> Why should you care if the caller uses the return value or not?

Nodiscard is a way of “enforcing” a contract with the user about how your code needs to be used in order to avoid undefined behaviour.

(I say “enforcing” in quotes because, instead of being an actual constraint, it’s merely an attribute - so a conforming compiler can happily ignore it)

Here are two examples of where it is useful:

- Returning a success code that must be checked before proceeding with an operation that could have bad consequences if the previous operation failed. Unchecked operations are one of the major sources of bugs in the wild, so no discard at least points the user to the potential problem.

- Returning something that doesn’t make any sense to immediately discard. This is usually down to a mistake - such as calling vector::empty thinking that it’s going to clear the vector, when it actually returns a bool telling you if it’s empty or not (an awful name, but then so is vector…). It makes no sense to check if it’s empty without using that result, so the warning indicates that the user has made a mistake.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: