mercredi 30 mars 2022

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?

Aucun commentaire:

Enregistrer un commentaire