检测成员变量的阴影 [英] Detecting shadowing of member variables
本文介绍了检测成员变量的阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一名成员的A类:
std::shared_ptr<class B> m_mySharedPtr;
我有一个初始化方法:
A::Init()
{
std::shared_ptr<class B> m_mySharedPtr = m_factory->CreateMySharedPtr();
}
我花了一些时间才意识到,在执行初始化之后,shared_ptr为空.这是因为我重新定义了成员,将其视为本地成员,因此在A :: Init()范围之外时被释放.
It took me some time to realize that after my Init the shared_ptr is Empty. That is because I re-define the member, treated as a local and thus released when out of A::Init() scope.
我打算写:
A::Init()
{
m_mySharedPtr = m_factory->CreateMySharedPtr();
}
为什么编译器不抱怨?至少是警告?类似于成员重新定义".
Why did the compiler not complain? At least a warning? Something like "member re-definition."
在特定情况下确实有效/有用吗?
Is it indeed valid/useful in a particular case?
也许我的警告级别太低.
Maybe my warning level is too low.
谢谢
Vincent
推荐答案
如果您使用的是GCC或Clang,请使用 -Wshadow
标志.您将获得如下编译器输出:
If you're using GCC or Clang, then use the -Wshadow
flag. You get compiler output like this:
test.cc:5:7: warning: declaration shadows a field of 'A' [-Wshadow]
std::shared_ptr<class B> m_mySharedPtr = m_factory->CreateMySharedPtr();
^
test.cc:2:15: note: previous declaration is here
std::shared_ptr<class B> m_mySharedPtr;
- 参考资料: http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Warning-Options.html#Warning-Options .
这篇关于检测成员变量的阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文