Gerald Agapov
Gerald Agapov

Reputation: 220

Why clang doesn't produce warning about shadowing?

Consider the following code:

class A {
  A(int x) {
    y_ = x;
  }
  void x() {
  }
  int y_;
};
int main() {
}

If I compile it with latest clang with use of -Weverything it won't produce any warning. But if I compile it with g++ with -Wall -Wshadow it will produce

x.cpp: In constructor ‘A::A(int)’:
x.cpp:2:12: warning: declaration of ‘x’ shadows a member of 'this' [-Wshadow]
   A(int x) {
        ^

Why these two produce different warnings? Who is right? Is it bug?

Upvotes: 2

Views: 834

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106244

Why shouldn't they produce different warnings? Neither is "right". The Standard doesn't mandate a warning for something like this, so it's entirely up to the compiler writers to decide what they think their users might find a warning useful.

Note that any confusion about which x was being used would likely result in either an attempt to "call" a variable (which can make sense for a functor) or to assign to or read from a function... many (but not all) such accidental users would be outright compiler errors anyway. For many people (including me) naming conventions ala member_variable_ remove potential for the parameter to clash with a member variable.

I've never wanted such a warning, and knowing GCC offers one and being a frequent and happy GCC user wouldn't lead me to turn it on, so it's arguable whether there's value in such a warning. Hard to know how often it might result in a bug being avoided, versus how often it might remove attention from more important warnings or actual coding, resulting in more bugs!

Upvotes: 2

Related Questions