简体   繁体   中英

Avoiding shared_ptr redirection

I'm storing a shared ptr and a reference to the shared object inside a wrapper. Does anyone see a chance of a memory leak? Just being cautious...

class B;
class A
{
public :
  typedef shared_ptr< B > PB;
  A( PB pb ) :
    m_pb( pb ),
    m_b( *pb )
  { }

  void someFunc()
  {
    // do something with m_b
  }

  PB getB()
  { 
    return m_pb; 
  }
  // in particular, no function returns a ref to B

private :
  PB m_pb;
  B &m_b;

};

I don't see any problem, as far as both members have the same scope. But a general rule does not recomend to use reference or naked pointer to an object stored in the shared_pointer, as far as lifetime of the object is managed by the shared pointer, and you have bad chance to get things out of your control.

PS In the comments KennyTM tells about check on NULL pointer first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM