简体   繁体   中英

Finding unused objects (non-primitive values)

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?

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.

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

I'm not sure if I'm missing something in the question but gcc/g++ has options which allow you to specify which warnings you want and which you don't. So simply just enabled the -Wunused-variable.

See here for more details: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Also, -Wall will turn this and many more useful warning on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM