Jean Catanho Jean Catanho - 1 year ago 75
C++ Question

How should a weak_ptr be initialized in a class constructor that receives a shared_ptr?

I have a class that receives a shared pointer in its constructor and stores it in a weak pointer but I'm not sure how (and where) to do this conversion.

class A {
A(std::shared_ptr<B> Bptr);

std::weak_ptr<B> m_Bptr;

Should I convert the
before passing to the constructor or not?

Does passing the
to the
through an initialization list like this
A(std::shared_ptr<B> Bptr) : m_Bptr(Bptr) { }
works as expected or I need to explicitly convert in the body of the constructor?

Answer Source
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r );

A constructor of weak_ptr takes a shared_ptr as argument. So, yes just passing the shared_ptr will work.

From cppreference:

Constructs new weak_ptr which shares an object managed by r. If r manages no object, *this manages no object too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download