Kylo
Kylo

Reputation: 2320

g++ does not show a 'unused' warning

I have a little piece of code in C++:

#include <iostream>
#include <iterator>
#include <string>

using namespace std;

int main() {

    int i=0;
    istream_iterator<string> EOS;
    double x;

    return 0;
}

Now i compile it with my g++ (GCC) 4.4.4

g++ -W -Wall -pedantic test.cc -o test

And get:

test.cc: In function 'int main()':
test.cc:9: warning: unused variable 'i'
test.cc:11: warning: unused variable 'x'

Why there is no warning for unused EOS?

Upvotes: 28

Views: 2465

Answers (3)

EboMike
EboMike

Reputation: 77752

Because you could have done that with a purpose. It's not a primitive. Maybe the constructor and destructor do something important?

MFC even had classes that operated that way, you could do this:

void foo()
{
    CWaitCursor cursor;

    [...]
}

That would display an hourglass icon for the duration of the function.

Upvotes: 4

James McNellis
James McNellis

Reputation: 355079

istream_iterator<string> has a constructor, so the declaration of EOS isn't really a no-op like the declarations of i and x are.

Often you want to declare a class-type object and then not do anything with it. For example, consider std::lock_guard in C++0x (boost::scoped_lock in Boost) or any other kind of scope guard class. You don't usually want to do anything with that kind of object, you just want to create the object so that its destructor get run at the end of the block to perform whatever cleanup needs to be performed.

Upvotes: 7

Thomas
Thomas

Reputation: 181785

It is not a primitive value, so its constructor and/or destructor might have desired side effects.

To illustrate that this happens in practice: I use a class to time sections of code, that looks roughly like this:

class Timed {
    double start;
    public:
        Timed() { start = now(); }
        ~Timed() { std::cout << (now() - start) << '\n'; }
}

So to measure how long a function takes, I simply do:

void slow() {
    Timed t;
    // heavy operation here...
}

The variable t never gets used, but it's still important to the behaviour of the code.

Upvotes: 39

Related Questions