In large C++ projects, certain functions return values that are crucial for correctness or safety. Ignoring these values can lead to subtle bugs. Instead of relying on manual code reviews to catch such issues, modern C++ provides a mechanism to alert developers when important return values are discarded. This tutorial explains how to produce warning on ignored values in C++.
C++ provides a modern, standardized way to tell the compiler to generate a warning when its return value is not used, using the [[nodiscard]] attribute (introduced in C++17).
#include <iostream>
[[nodiscard]] std::string add_txt(const std::string &file) {
return file + ".txt";
}
int main() {
std::string file = "test";
add_txt(file); // warning: ignoring return value
file = add_txt(file); // OK
(void) add_txt(file); // OK
std::cout << file << std::endl;
return 0;
}
The (void) cast can be used to explicitly discard a return value when ignoring it is intentional. This makes the intention clear to both the compiler and readers, preventing unnecessary warnings.
Leave a Comment
Cancel reply