std::ignore for ignoring unused variable

gaurav bharadwaj picture gaurav bharadwaj · Sep 28, 2016 · Viewed 10.9k times · Source

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;
}

Answer

Alexey Guseynov picture Alexey Guseynov · Sep 28, 2016

In such case just don't write variable name:

void func(int /*i*/)
{
    ...
}

@Hayt's answer is good, but uses latest version of C++ which is not always available. Not writing variable name is an old convention to tell a compiler that you don't actually need the variable.

For an updated question I would go for a static instance of a class with needed initialization in a constructor. I say initialization because the only reason I can make for having such function is to initialize some global object.

class SomethingInitializer {
public:
    SomethingInitializer() {
        func_returnSomething();
    }
    ~SomethingInitializer() {
        // Note, that when you initialize something it is a good practice to deinitialize it at the end, and here is a proper place for that.
    }
};

void func() {
    static SomethingInitializer initializer;
}

This solution has a small bonus: SomethingInitializer is RAII compliant. So when application terminates destructor is called and it can make deinitialization.

Note, that compiler knows that classes may do something useful in constructor and destructor, so it will not complain for unused variable.