5

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?

galinette
  • 8,896
  • 2
  • 36
  • 87
  • See [How do you disable the unused variable warnings coming out of gcc?](http://stackoverflow.com/q/15053776/1708801) specifically [this answer](http://stackoverflow.com/a/23331548/1708801) – Shafik Yaghmour Mar 25 '15 at 09:26
  • You read my question too fast... I don't want that, because these warnings are interesting – galinette Mar 25 '15 at 09:37
  • 1
    Please read the specific answer I point to which shows you how to disable it for one variable at a time. – Shafik Yaghmour Mar 25 '15 at 09:38
  • 2
    Please post some actual code, as my g++ 4.9.2 (admittedly not exactly your compiler, but very close) does not give unused variable warnings as soon as a constructor is invoked. Even if that constructor is literally empty. You might also wish to share how you invoke g++ exactly. – danielschemmel Mar 25 '15 at 09:38
  • @gha.st : You are right : adding an empty ctor solves the issue. Do you want to enter a detailed answer? – galinette Mar 25 '15 at 09:45
  • @ShafikYaghmour : my bad, I read your comment too fast... Thanks for the link. I'm not fond of pragmas since they are absolutely not portable, but this works – galinette Mar 25 '15 at 09:48

2 Answers2

6

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.

danielschemmel
  • 10,885
  • 1
  • 36
  • 58
1

For C++ 17 and beyond, you can use [[maybe_unused]]:

[[maybe_unused]] OpenEXRMutexLock lock;
xuhdev
  • 8,018
  • 2
  • 41
  • 69