weak_ptr 应该如何在接收 shared_ptr 的 class 构造函数中初始化?
How should a weak_ptr be initialized in a class constructor that receives a shared_ptr?
我有一个 class 在其构造函数中接收共享指针并将其存储在弱指针中,但我不确定如何(以及在何处)进行此转换。
class A {
public:
A(std::shared_ptr<B> Bptr);
private:
std::weak_ptr<B> m_Bptr;
};
我是否应该在传递给构造函数之前转换 shared_ptr
?
通过像这样的初始化列表 A(std::shared_ptr<B> Bptr) : m_Bptr(Bptr) { }
将 shared_ptr
传递给 weak_ptr
是否按预期工作,或者我需要在构造函数的主体中显式转换?
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r );
weak_ptr
的构造函数将 shared_ptr
作为参数。所以,是的,只要传递 shared_ptr
就可以了。
来自 cppreference:
Constructs new weak_ptr which shares an object managed by r. If r
manages no object, *this manages no object too.
我有一个 class 在其构造函数中接收共享指针并将其存储在弱指针中,但我不确定如何(以及在何处)进行此转换。
class A {
public:
A(std::shared_ptr<B> Bptr);
private:
std::weak_ptr<B> m_Bptr;
};
我是否应该在传递给构造函数之前转换 shared_ptr
?
通过像这样的初始化列表 A(std::shared_ptr<B> Bptr) : m_Bptr(Bptr) { }
将 shared_ptr
传递给 weak_ptr
是否按预期工作,或者我需要在构造函数的主体中显式转换?
template< class Y >
weak_ptr( const std::shared_ptr<Y>& r );
weak_ptr
的构造函数将 shared_ptr
作为参数。所以,是的,只要传递 shared_ptr
就可以了。
来自 cppreference:
Constructs new weak_ptr which shares an object managed by r. If r manages no object, *this manages no object too.