我有一个类层次结构如下:
class BaseSession : public boost::enable_shared_from_this<BaseSession> class DerivedSessionA : public BaseSession class DerivedSessionB : public BaseSession
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
由于我正在使用shared_ptr来管理会话,所以这是正常的.最近,我发现我使用shared_ptr对于这种情况并不是最佳的.那是因为这些会话是每个客户端保持一个套接字的单例对象.如果套接字重新连接,则会话副本用于成为僵尸.
作为解决方法,我开始通过引用传递shared_ptr而不是副本.这解决了僵尸问题.
理想情况下,我觉得我应该使用unique_ptr存储会话,然后传递给其他函数的引用.这打开了一整套蠕虫.
如何将基类unique_ptr对象转换为派生类unique_ptr对象?以下行的unique_ptr版本是什么?
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
我只想要一个会话对象的副本,其他的都应该是引用的.
解决方法
@H_404_23@ 除非您要转让std :: unique_ptr< T>的所有权,否则您的函数应该指向或指向T.所以Func的签名应该是Func(DerivedSessionA *)
然后你的电话可能看起来像:
std::unique_ptr<BaseSession> ptr; // Initialize it with correct value Func(dynamic_cast<DerivedSessionA*>(ptr.get()));
Func(dynamic_cast<DerivedSessionA*>(this));