Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Unreferenced local variable

Tags:

c++

When I provide a constructor for class A, I don't get the unreferenced local variable why? What does the empty constructor do to eliminate the warning?

class A
{
public:
   A() {}
};

int main()
{
   A a;
}
like image 268
user32234 Avatar asked Feb 24 '23 09:02

user32234


2 Answers

This is only a theory, but because a constructor may contain code that can cause side effects, someone may decide to construct an unused object just to run that code. If you have no constructor and never reference an object that you've constructed, then it can safely be determined that the object has no purpose.

like image 81
Jacob Avatar answered Mar 06 '23 15:03

Jacob


For example if A is something that holds a mutex lock (and release the lock when destructed), then this code

int main()
{
    A a;
    // other actions
}

is able to keep this function thread-safe, even a does not be referenced.

like image 34
neuront Avatar answered Mar 06 '23 15:03

neuront