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::ignoremay 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]]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
And also for many more:
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_unuseddeclared variables.