Search code examples
c++gccwarningsraiiunused-variables

gcc warns about unused RAII variable


I have a class called MutexLock, which does as it sounds : it locks a mutex on construction, and releases it upon destruction:

    class OpenEXRMutexLock
    {
#ifndef HAVE_PTHREADS
    public:
        OpenEXRMutexLock() : lock(openEXRmutex) { }
    private:
        std::unique_lock<std::mutex> lock;
#endif
    };

When HAVE_PTHREADS is defined, gcc 4.9.1 complains about unused variable whenever I do :

OpenEXRMutexLock lock;

Of course, the class is meant to be never used outside construction and automatic destruction.

Currently, I did something ugly : I added

void OpenEXRMutexLock::dummyFuncAvoidingWarnings() const {}

And call it everywhere:

OpenEXRMutexLock lock;
lock.dummyFuncAvoidingWarnings(); //Eeerk

Is there a way to avoid this without disabling unused variable warnings on the full project?


Solution

  • GCC is smart enough to detect if the definition of a variable invokes a constructor call. In your case, ensuring that a constructor is indeed invoked (even an empty one) will mark the variable definition as having a side-effect and ensure that you will not get a warning anymore.

    This behavior holds true even for ancient versions of GCC.