The [[nodiscard("reason")]] Attribute
Explore the improvements to the nodiscard attribute in C++20, including the ability to specify reasons for warnings and to apply nodiscard to constructors. Understand how these enhancements aid in detecting discarded return values, prevent memory leaks, and improve code correctness by providing clearer compiler messages.
We'll cover the following...
C++17 introduced the new attribute [[nodiscard]] without a reason. C++20 added the possibility to add a message to the attribute.
Discarding objects and error codes
Thanks to perfect forwarding and parameter packs, the factory function create (at line 7) can call any constructor and return a heap-allocated object.
The program has many issues. First, line 27 has a memory leak, because the int created on the heap is never deleted. Second, the error code of the function errorProneFunction (at line 29) is not checked.
Lastly, the constructor call MyType(5, true) (at line 31) creates a temporary, which is created and immediately destroyed. This is ...