Reputation: 326
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
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