gcc warns about unused RAII variable
Asked Answered
F

2

6

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?

Fever answered 25/3, 2015 at 9:23 Comment(6)
See How do you disable the unused variable warnings coming out of gcc? specifically this answerTasiatasiana
You read my question too fast... I don't want that, because these warnings are interestingFever
Please read the specific answer I point to which shows you how to disable it for one variable at a time.Tasiatasiana
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.Sinusoidal
@gha.st : You are right : adding an empty ctor solves the issue. Do you want to enter a detailed answer?Fever
@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 worksFever
S
8

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.

Sinusoidal answered 25/3, 2015 at 9:51 Comment(0)
H
1

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

[[maybe_unused]] OpenEXRMutexLock lock;
Herwick answered 24/2, 2023 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.