The [[nodiscard("reason")]] Attribute
Understand the use of the '[[nodiscard("reason")]]' attribute in C++20.
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
Press + to interact
#include <utility>struct MyType {MyType(int, bool) {}};template<typename T,typename ... Args>T* create(Args&& ... args) {return new T(std::forward<Args>(args)...);}enum class ErrorCode{Okay,Warning,Critical,Fatal};ErrorCode errorProneFunction() {return ErrorCode::Fatal;}int main() {int* val = create<int>(5);delete val;create<int>(5);errorProneFunction();MyType(5, true);}
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 ...