How to get g++ to warn on unused member variables

2019-04-05 12:08发布

g++ generates warnings for unused local variables. Is it possible to have g++ warn for unused class member variables and/or global variables?

class Obj {
 public:
  Obj(int a, int b) : num1(a), num2(b) {}
  int addA(int i) {
    return i + num1;
  }

 private:
  int num1;
  int num2;
};

How do I get g++ to warn me that num2 is unused?

UPDATE: I am currently compiling with:

g++ -Wall -Wextra -pedantic *.cc -o myprogram 

标签: c++ g++
3条回答
放我归山
2楼-- · 2019-04-05 12:38

Clang's -Wunused-private-field enables the warning you're asking for. On your code base, it shows:

$ clang -Wunused-private-field /tmp/nic.cpp  
/tmp/nic.cpp:10:22: warning: private field 'num2' is not used [-Wunused-private-field]
             int num2;
                 ^
1 warning generated.
查看更多
太酷不给撩
3楼-- · 2019-04-05 12:51

You can use cppcheck (download). cppcheck --enable=style does exactly what you need, among other useful things.

查看更多
唯我独甜
4楼-- · 2019-04-05 12:57

I'm not aware of any such warning. Additionally I'll speculate that the reason it doesn't exist is because it can't be reliably generated in all cases, so they elected to not spend effort making it work for some subset of cases. For example, if the class friends another function that's in a library, the compiler would have no way of knowing if that library mutated any particular class attribute or not.

查看更多
登录 后发表回答