问题
I have a class A with a member:
std::shared_ptr<class B> m_mySharedPtr;
I have an Init method:
A::Init()
{
std::shared_ptr<class B> m_mySharedPtr = m_factory->CreateMySharedPtr();
}
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.
I meant to write:
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.
Thanks,
Vincent
回答1:
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;
- Reference: http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Warning-Options.html#Warning-Options.
来源:https://stackoverflow.com/questions/22773732/detecting-shadowing-of-member-variables