maybe unused
suggest changeThe [[maybe_unused]] attribute (C++17) indicates that certain logic might not be used. That often depends on preprocessor conditions. Compilers can warn about unused variables and unused functions, and the attribute suppresses those warnings by stating the intent.
A typical example of variables which are needed in debug builds while unneeded in production are return values indicating success. In the debug builds, the condition should be asserted, though in production these asserts have been removed.
[[maybe_unused]] auto mapInsertResult = configuration.emplace("LicenseInfo", stringifiedLicenseInfo);
assert(mapInsertResult.second); // We only get called during startup, so we can't be in the map
A more complex example is helper functions in an unnamed namespace. A compiler may warn if a function is defined and never called. A declaration by itself does not produce that warning. Guarding the helpers with the same preprocessor conditions as the caller is ideal. When that becomes hard to maintain, [[maybe_unused]] is an alternative. A string literal is not allowed in #if, so the condition has to test a macro name.
namespace {
[[maybe_unused]] std::string createWindowsConfigFilePath(const std::string &relativePath) {
return relativePath;
}
// TODO: Reuse this on BSD, macOS, ...
[[maybe_unused]] std::string createLinuxConfigFilePath(const std::string &relativePath) {
return relativePath;
}
}
std::string createConfigFilePath(const std::string &relativePath) {
#ifdef _WIN32
return createWindowsConfigFilePath(relativePath);
#elif defined(__linux__)
return createLinuxConfigFilePath(relativePath);
#else
#error "OS is not yet supported"
#endif
}
See the proposal for more detailed examples on how [[maybe_unused]] can be used.