关于隐藏成员变量的警告? [英] Warning about hiding member variables?
问题描述
以下代码段具有内存泄漏,我花了太多时间追逐。问题是在Foo()内部,局部变量x_隐藏了成员变量x_。这也很烦人,因为编译器可以警告我。 GCC中是否有这样的警告标志? (对于好奇:我已经到达了buggy代码,首先使用局部变量,然后将其更改为成员变量,但忘记删除类型声明。)
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); //宏以防止复制/分配。
}
使用-Wshadow。 p>
顺便说一句,-W和-Wall都不会启用-Wshadow。
让编译器帮助避免这种问题,但是如果你使用惯例,帮助避免创建它的第一个地方,这样保留成员变量的形式 x _
的名称,甚至不必要,而不是本地变量。
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.
}
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.
这篇关于关于隐藏成员变量的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!