Is it a good approach to use std::ignore
for ignoring unused variables?
Suppose I have a function like this:
void func(int i)
{
//for some reason, I don't need i anymore but I cannot change signature of function
std::ignore = i;
}
Additional Info
This was one example and some answers suggested to use anonymous variables. But how would I do it for other cases, like:
int Thread_UnSafe_func_returnSomething():
void func()
{
// To make it thread safe
// Also it is required to call only once
static int i = Thread_UnSafe_func_returnSomething();
std::ignore = i;
}
std::ignore
may work but it is intended to be used for tuples. So you need to include the tuple header and who knows what operations are done for the assignment. This also may break in another c++ version because it was never documented to be used that way.
A better way for this is the C++17 attribute [[maybe_unused]]
void func([[maybe_unused]] int i)
{
}
It places the declaration right at the variable declaration, so you don't have to declare it in an extra line/statement.
The same can be used for local (and local-static) variables
...
[[maybe_unused]] static int a = something();
...
And also for many more:
Appears in the declaration of a class, a typedef, a variable, a nonstatic data member, a function, an enumeration, or an enumerator. If the compiler issues warnings on unused entities, that warning is suppressed for any entity declared maybe_unused.
See http://en.cppreference.com/w/cpp/language/attributes
As for the people concerned that you can still use the variables after you declare them unused:
Yes, this is possible but (at least with clang) you will get warnings in case you use maybe_unused
declared variables.