Say I have
[[nodiscard]] int foo ()
{
return 0;
}
int main ()
{
foo ();
}
then
error: ignoring return value of ‘int foo()’, declared with attribute nodiscard [-Werror=unused-result]
but if
int x = foo ();
then
error: unused variable ‘x’ [-Werror=unused-variable]
Is there a clean way of telling the compiler "I want to discard this [[nodiscard]]
value"?
The WG14 nodiscard proposal discusses the rationale for allowing the diagnostic to be silenced by casting to void. It says casting to void is the encouraged (if non-normative) way to silence it which follows what the existing implementation do with
__attribute__((warn_unused_result))
:The C++ way would be
static_cast<void>
.See the draft C++ standard [[dcl.attr.nodiscard]p2:
This is a note, so non-normative but basically this is what existing implementations do with
__attribute__((warn_unused_result))
. Also, note a diagnostic for nodiscard is also also non-normative, so a diagnostic for violating nodiscard is not ill-formed but a quality of implementation just like suppressing via a cast to void is.see the clang document on nodiscard, warn_unused_result: