tags:

views:

189

answers:

3

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.
}
+16  A: 

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.

Nathan Kitchen
+1. You *even* answered the actual question being asked!
j_random_hacker
It appears to me that OP has such a convention, but has had a "thinko" and typed "string* x_ =" instead of the "x_ =" that was actually intended.
Steve Jessop
IMHO, it's far better to have your editor highlight local and member variables in contrasting ways than it is to add a hungarian wart to the name.
rmeador
@rmeador. I'm sorry but that is a pretty dangerous statement. If you ever need to write code that is to be ported to other platforms, you simply cannot trust that all editors will do this. It's always best to write code that is as robust as you can make it.
Richard Corden
+5  A: 

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_.

ChrisW
+1, very common convention.
Emil H
It is also not uncommon convention for private member functions. It helps to catch quick and clearly in a second what's private.
mloskot
A: 

We use these warts on the beginnings of names - a_ argument d_ data member s_ static data in class f_ static data in file

... and no wart for local variables.

Truly, the Lakos book is your friend.

Phone Guy