C++ Warning if re-declaring member variable in fun

2019-07-08 06:18发布

问题:

Given a structure such as below

class A {
  int test;
  void f() { int test; }
}

I just had a curious case in which the code in f(), when referring to test, compiled under VS2010, correctly referred to the function local variable, however, when compiled under gcc, incorrectly referred to the member variable. Took me quite a while to track down.

Anyway, question is, is there an option in gcc or VS to enable compiler warnings every time a member variable is re-declared in a local function scope?

回答1:

In GCC, -Wshadow. From the documentation:

Warn whenever a local variable or type declaration shadows another variable, parameter, type, or class member (in C++), or whenever a built-in function is shadowed. Note that in C++, the compiler will not warn if a local variable shadows a struct/class/enum, but will warn if it shadows an explicit typedef.



回答2:

I don't know if any such option exists.

But if it doesn't exist, then you can do the following. In fact, the naming convention is preferred even if there exists some compiler option to avoid the problem in the question, for it covers broader area of concerns:

class A {
  int m_test;   //use some naming conventions!
  void f() { int test; }
};

That is, use some rules in naming the member variables, such as, prefix each with m_ as in m_test, Or use suffix as in test_. This is the usual approach adopted by many programmers, and in many companies, there is similar rules which they impose when coding.

Such naming conventions not only help avoiding the problem you came across, it also increases readability and maintainability, as the name test suggests nothing as to whether it is local variable or member variable in the absence of naming conventions. But once you adopt some naming conventions, such things become clear.