Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding unused objects (non-primitive values)

Tags:

c++

g++

Follow up to question: g++ does not show a 'unused' warning.

I fully understand why g++ doesn't warn about these variables, but I would like it to somehow find them anyway. The code I'm working on doesn't have any of those special cases, so a single FloatArray x; is almost definitely left-overs.

Even If i have to mark individual classes (Such as warning for unused FloatArray-objects) it would be very useful. What can I do?

like image 227
Mikael Öhman Avatar asked Jan 18 '12 20:01

Mikael Öhman


2 Answers

Well, with GCC the following code does warn as you want:

struct Foo
{
};
struct Bar
{
    Foo f;
};
int main()
{
    Bar b; //warning: unused variable 'b' 
}

But if you add a constructor/destructor to the Foo or Bar struct, even a trivial one, it will not warn.

struct Foo
{
    Foo() {}
};
struct Bar
{
    Foo f;
};
int main()
{
    Bar b; //no warning! It calls Foo::Foo() into b.f
}

So the easiest way to regain the warning is to compile all the relevant constructors AND destructors conditionally:

struct Foo
{
#ifndef TEST_UNUSED
    Foo() {}
#endif
};
struct Bar
{
    Foo f;
};
int main()
{
    Bar b; //warning!
}

Now compile with g++ -DTEST_UNUSED to check for extra unused variables.

Not my brightest idea, but it works.

like image 162
rodrigo Avatar answered Sep 24 '22 10:09

rodrigo


Well, basically you want to create some sort of simple static analysis tool plugged in GCC ? If that's so, you could start by using MELT to quickly implement an unused variable printer.

http://gcc.gnu.org/wiki/MELT%20tutorial

like image 27
NewbiZ Avatar answered Sep 25 '22 10:09

NewbiZ