C++17 introduces the [[nodiscard]]
attribute, which allows programmers to mark functions in a way that the compiler produces a warning if the returned object is discarded by a caller; the same attribute can be added to an entire class type.
I've read about the motivation for this feature in the original proposal, and I know that C++20 will add the attribute to standard functions like std::vector::empty
, whose names do not convey an unambiguous meaning regarding the return value.
It's a cool and a useful feature. In fact, it almost seems too useful. Everywhere I read about [[nodiscard]]
, people discuss it as if you'd just add it to a select few functions or types and forget about the rest. But why should a non-discardable value be a special case, especially when writing new code? Isn't a discarded return value typically a bug or at least a waste of resources?
And isn't one of the design principles of C++ itself that the compiler should catch as many errors as possible?
If so, then why not add [[nodiscard]]
in your own, non-legacy code to almost every single non-void
function and almost every single class type?
I've tried to do that in my own code, and it works fine, except it's so terribly verbose that it starts to feel like Java. It would seem much more natural to make compilers warn about discarded return values by default except for the few other cases where you mark your intention[*].
As I've seen zero discussions about this possibility in standard proposals, blog entries, Stack Overflow questions or anywhere else on the internet, I must be missing something.
Why would such mechanics not make sense in new C++ code? Is verbosity the only reason not to use [[nodiscard]]
almost everywhere?
[*] In theory, you may have something like a [[maydiscard]]
attribute instead, which could also be retroactively added to functions like printf
in standard-library implementations.
operator =
for example. Andstd::map::insert
.const
can bloat an otherwise "simple" class (or rather "plain old data object") considerably in C++.std::vector
orstd::unique_ptr
, of which you just need data members in your class definition. I've worked with both languages; Java is an okayish language, but it is more verbose.