Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc -Wshadow is too strict?

In the following example:

class A
{
  public:
    int len();
    void setLen(int len) { len_ = len; } // warning at this line
  private:
    int len_;
};

gcc with -Wshadow issue a warning:

main.cpp:4: warning: declaration of `len' shadows a member of `this'

function len and integer len are of different type. Why the warning?

Update

I see there's a wide consensus of what "shadow" means. And from a formal point of view, the compiler does exactly what it's meant to do.

However IMHO, the flag is not practical. For example commonly used setter/getter idiom :

class A {
   void prop(int prop);  // setter
   int prop() const;     // getter

   int prop;
};

It would be nice if there was a warning flag that won't issue warning in the case, but will warn in case "int a" hides "int a".

Adding -Wshadow on my legacy code issues tons of warnings, while from time to time I discover bugs caused by "shadowing" problem.

I don't mind how it will be called "-Wmuch_more_practical_and_interesting_shadow" or "-Wfoooooo".

So, are there other gcc warning flags that do what I described?

Update 2

I'm not the only one who thinks -Wshadow is somehow not useful link text. I'm not alone :) Less strict checking could be much more useful.

like image 658
dimba Avatar asked Jun 02 '10 14:06

dimba


2 Answers

This seems to be solved on newer versions of GCC.

From version 4.8 changelog:

The option -Wshadow no longer warns if a declaration shadows a function declaration,
unless the former declares a function or pointer to function, because this is a common
and valid case in real-world code.

And it references Linus Torvalds's thoughts on the subject: https://lkml.org/lkml/2006/11/28/253

Unfortunately the newest compiler of the embedded system where I'm currently working is still based on gcc 4.6.

like image 103
mMontu Avatar answered Oct 25 '22 20:10

mMontu


The fact that the parameter has a different type from the member function doesn't affect the fact that the parameter shadows the member function.

Why would you expect there not to be a warning about this?

like image 20
James McNellis Avatar answered Oct 25 '22 19:10

James McNellis