Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning about hiding member variables?

Tags:

c++

gcc

The following code snippet has a memory leak that I spent too much time chasing down. The problem is that inside Foo(), the local variable x_ hides the member variable x_. It's quite annoying too, because the compiler could have warned me about it. Is there a flag in GCC for such a warning? (For the curious: I have arrived at the buggy code by first using a local variable, then changing it to a member variable, but forgetting to remove the type declaration.)

struct A {
  A() x_(NULL) {}

  ~A() {
    delete x_;
  }

  void Foo() {
    HugeThingy* x_ = new HugeThingy();
    x_->Bar("I. Need. Garbage. Collection. Now.");
  }

  HugeThingy* x_;

  DISALLOW_COPY_AND_ASSIGN(A);  // Macro to prevent copy/assign.
}
like image 512
Lajos Nagy Avatar asked May 26 '09 17:05

Lajos Nagy


2 Answers

Use -Wshadow.

By the way, neither -W nor -Wall enables -Wshadow.

It's nice to have the compiler help avoid this kind of problem, but that won't even be necessary if you use conventions that help avoid creating it in the first place, such reserving names of the form x_ for member variables, not local variables.

like image 165
Nathan Kitchen Avatar answered Oct 13 '22 01:10

Nathan Kitchen


FWIW I wouldn't have this problem because I use a naming convention to distinguish member data from local variables: my member data identifiers are invariably prefixed with m_.

like image 28
ChrisW Avatar answered Oct 13 '22 00:10

ChrisW