g++ does not show a 'unused' warning

后端 未结 3 1789
一个人的身影
一个人的身影 2020-11-29 11:13

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

#include 
#include 
#include 

using namespace std;

int main() {

    in         


        
相关标签:
3条回答
  • 2020-11-29 11:34

    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.

    0 讨论(0)
  • 2020-11-29 11:36

    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.

    0 讨论(0)
  • 2020-11-29 11:40

    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.

    0 讨论(0)
提交回复
热议问题