Jean Catanho
Jean Catanho

Reputation: 326

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 {
    public:
        A(std::shared_ptr<B> Bptr);

    private:
        std::weak_ptr<B> m_Bptr;
};

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

Does passing the shared_ptr to the weak_ptr 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?

Upvotes: 1

Views: 5817

Answers (1)

themagicalyang
themagicalyang

Reputation: 2553

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.

Upvotes: 6

Related Questions