c++11g++compiler-warningsgcc-warning

Why there is unused-but-set variable-warning with pointers


I have the following code:

#include <iostream>

class Test {
public:
    
    Test(int i) {
        initialize(i);
    }
    
    void initialize(int i) {
        std::cout<<"i: "<<i<<std::endl;
    }
};



int main() {
    Test* obj1(nullptr);
    obj1 = new Test(2);
    
    Test* obj2(nullptr);
    obj2 = new Test(2);
    obj2->initialize(3);    
    
    return 0;
}

When I compile as such (GCC v11.2.0):

g++ -Wall --std=c++11 main.cpp

I see the following warning:

main.cpp: In function ‘int main()’:
main.cpp:25:15: warning: variable ‘obj1’ set but not used [-Wunused-but-set-variable]
   25 |         Test* obj1(nullptr);
      |               ^~~~

My question is why is there a warning for obj1, but not obj2 when they do almost the same thing?


Solution

  • The key thing to realize here is that you actually have FOUR objects in your code -- two instances of the class Test and two pointers. The instances of Test don't have names (they're created with new), while the pointers do have names (obj1 and obj2).

    The warning here is about the pointer object obj1 which is only ever assigned to and not used. The fact that the object it points at after the final assignment has had various side effects prior to that assignment is not relevant. You could remove the declaration an assignment (but not the new call in the assignment) without affecting the behavior or output of your program.

    int main() {
        new Test(2);
        
        Test* obj2(nullptr);
        obj2 = new Test(2);
        obj2->initialize(3);    
        
        return 0;
    }