如何使用unique_ptr执行dynamic_cast? [英] How to do perform a dynamic_cast with a unique_ptr?
问题描述
我有一个类层次结构如下:
I have a class hierarchy as follows:
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
对于这种情况不是最佳的。这是因为这些会话是单个对象,每个客户端维护一个套接字。如果socket重新连接,会话副本用于变为僵尸。
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
object? 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 *)
,然后您的呼叫可能如下: / p>
and then your call may look like:
std::unique_ptr<BaseSession> ptr; // Initialize it with correct value
Func(dynamic_cast<DerivedSessionA*>(ptr.get()));
或者你似乎直接从 code>:
Or as you seems to call it directly from a method in BaseSession
:
Func(dynamic_cast<DerivedSessionA*>(this));
这篇关于如何使用unique_ptr执行dynamic_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!