C++ notes: nodiscard attribute

About using the [[nodiscard]] attribute for your functions.

Modern C++ offers a [[nodiscard]] which can be added to a function. Adding the keyword to your functions makes the compiler throw a warning whenever a function with a return type is called without using the returned value. In the beginning this might seem as something which would be clever to be offered as the default option. Nevertheless, the idea was introduced quite late (I think it was C++17) and all of a sudden a lot of legacy code would throw thousands of warnings it it would be added as default. Therefore, one needs to specifically add the keyword if you want the compiler to throw this error.

I mostly use the attribute for functions that have no effect beside e.g. returning a value (could be some access point to a private class member or a pure calculation). If the user would discard the value returned from the function, he/she is clearly misusing the interface and a warning is appropriate. Other guidelines actually suggest not throwing a warning as long as not using the return value does not hurt (i.e. let the user call a function which has no effect but do not throw a warning).

Btw. if you want it as the default behavior that your compiler throws a warning at you when a return value remains unused, you can most likely add the -Wunused-result to e.g. g++.

Some links

Leave a Reply

Your email address will not be published. Required fields are marked *