Detecting shadowing of member variables

旧街凉风 提交于 2021-01-28 06:49:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!