Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c++ - Warning about hiding member variables?

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.
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...