A variable not detected as not used

前端 未结 3 1963
别那么骄傲
别那么骄傲 2021-01-18 09:41

I am using g++ 4.3.0 to compile this example :

#include 

int main()
{
  std::vector< int > a;
  int b;
}

If I compile

相关标签:
3条回答
  • 2021-01-18 10:25

    a is not a built-in type. You are actually calling the constructor of std::vector<int> and assigning the result to a. The compiler sees this as usage because the constructor could have side effects.

    0 讨论(0)
  • 2021-01-18 10:40

    In theory, the default constructor for std::vector<int> could have arbitrary side effects, so the compiler cannot figure out whether removing the definition of a would change the semantics of the program. You only get those warning for built-in types.

    A better example is a lock:

    {
        lock a;
        // ...
        // do critical stuff
        // a is never used here
        // ...
        // lock is automatically released by a's destructor (RAII)
    }
    

    Even though a is never used after its definition, removing the first line would be wrong.

    0 讨论(0)
  • 2021-01-18 10:45

    a is actually used after it is declared as its destructor gets called at the end of its scope.

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