如何使用unique_ptr执行dynamic_cast? [英] How to perform a dynamic_cast with a unique_ptr?
问题描述
我的类层次结构如下:
class BaseSession : public boost::enable_shared_from_this<BaseSession>
class DerivedSessionA : public BaseSession
class DerivedSessionB : public BaseSession
在派生类函数中,我定期调用这样的函数:
Within the derived class functions, I regularly call functions like this:
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
由于我正在与shared_ptr
一起管理会话,所以一切正常.最近,我发现shared_ptr
的使用不适用于这种情况.这是因为这些会话是单例对象,每个客户端维护一个套接字.如果重新连接套接字,则会话副本曾经成为僵尸.
Since I was working with shared_ptr
to manage the sessions, this was working fine. Recently, I discovered that my use of shared_ptr
is not optimal for this case. That is because these sessions are singleton objects that maintain one socket per client. If socket is reconnected, the session copies used to become zombies.
作为解决方法,我开始通过引用而不是副本传递shared_ptr
.这样就解决了僵尸问题.
As workaround, I started passing shared_ptr
by reference rather than copies. This solved the zombie problem.
理想情况下,我觉得我应该使用unique_ptr
来存储会话,然后将引用传递给其他函数.那打开了整罐蠕虫.
Ideally, I felt I should be using unique_ptr
to store the session and then pass references to other functions. That opened a whole can of worms.
如何将基类unique_ptr
对象转换为派生类unique_ptr
对象?下一行的unique_ptr
版本是什么?
How do I cast a base class unique_ptr
object to derived class unique_ptr
object? What is the unique_ptr
version of the following line?
Func(boost::dynamic_pointer_cast<DerivedSessionA>(shared_from_this()));
我只想要会话对象的一个副本,其他所有内容都应该引用.
I just want one copy of the session object, everything else should be reference.
推荐答案
除非您要转让对std::unique_ptr<T>
的所有权,否则您的函数应使用指向或引用T
的指针.
Unless you want to transfer ownership of your std::unique_ptr<T>
, your function should take pointer or reference to T
.
所以Func
的签名应该类似于Func(DerivedSessionA*)
So signature of Func
should be something like Func(DerivedSessionA*)
然后您的呼叫可能看起来像:
and then your call may look like:
std::unique_ptr<BaseSession> ptr; // Initialize it with correct value
Func(dynamic_cast<DerivedSessionA*>(ptr.get()));
或者您似乎直接从BaseSession
中的方法调用它:
Or as you seems to call it directly from a method in BaseSession
:
Func(dynamic_cast<DerivedSessionA*>(this));
这篇关于如何使用unique_ptr执行dynamic_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!