Search⌘ K
AI Features

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.

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

C++
#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 constructor call MyType(5, true) (at line 31) creates a temporary, which is created and immediately destroyed. This is ...