Question

I have some code that I put in a destructor to ensure it is run both on normal exit and exception stack unwinding:

struct withProtectedClose {

  ~withProtectedClose() {
    // Do some cleanup here...
  }
};

void test() {
  withProtectedClose close;

  // Do some work before closing
}

Yet the g++ compiler (g++ (GCC) 3.4.6 20060404 (Red Hat 3.4.6-11)) is complaining:

test.cpp: In function `void test()':
test.cpp:28: warning: unused variable 'close'

I can silence it by referring to the variable somehow, but that muddies the code only to silence the compiler, not how I want my code influenced.

Shouldn't the fact that there is a destructor be enough to clue the compiler in that it makes no difference that there is no use of the variable after construction?

Assuming the compiler cannot be shut up while still getting notices of legitimate unused variables, is there a way to silence this one only other than by using it?

Was it helpful?

Solution

I'd tend to think it is a bug in the compiler. It is still present in g++ 4.7.1.

As a work around, you may try to define a constructor which does nothing. It suppresses the warning with g++ 4.7.1, I don't know with 3.4.6.

OTHER TIPS

Since it seems to be solely a GCC issue, you can "fix" it by declaring your struct like this:

struct __attribute__ ((__unused__)) withProtectedClose

This reliably silences the warning on my version 4.6.3 compiler (and the destructor is demonstrably run, in accordance with the standard). It will however still warn you about unused variables otherwise.

Most of the time, it's a mistake that you really want to know about, so turning off the warning (-Wno-unused-variable) alltogether is not a good alternative. If for no other reason, one will want to remove (unintentionally) unused variables because they confuse people reading the code and put needless burden on the optimizer.

If you need to be portable, use a macro to encapsulate the attribute stuff (empty macro on non-GCC).

To address the actual question "Should compilers ignore unused variables that result in constructors or destructors being run?" -- No.

The C++ standard states [3.7.3.3]:

If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.

Insofar, a compiler is not allowed to ignore the variable. It is, however, allowed to warn about something that is often unintentional.

MSVC doesn't issue this warning in such a case. If your gcc version does, try suppressing it this way:

withProtectedClose close; 
(close); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top