vincentB
vincentB

Reputation: 128

Detecting shadowing of member variables

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

Upvotes: 1

Views: 780

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

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;

Upvotes: 3

Related Questions