如何投射 c++智能指针向上和向下
两个客户端在消息正文中的消息层之上相互通信
,我需要包含一个指向任何数据类型的字段。
从客户端 A,我将该字段作为 shared_ptr
发送到消息层。 我在消息层中将该字段定义为 shared_ptr
。 但如何在客户端 B 中将该字段转换回 shared_ptr
呢?
或者我应该在消息层中将 shared_ptr
定义为其他内容?
谢谢
two clients communicate to each other on top of a message layer
in the message body, I need include a field pointing to any data type
From client A, I send the field as a shared_ptr<TYPEA>
to the message layer.
I define this field as a shared_ptr<void>
in the message layer.
But how can I convert this field back to shared_ptr<TYPEA>
in client B?
Or should I define shared_ptr<void>
in message layer as something else?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 boost::shared_ptr 那么您可以使用各种 XXX_ptr_cast<>() 函数(static_ptr_cast、dynamic_ptr_cast...)。
如果您使用的是 MSVC 2010 版本,我还无法找到这些功能的实现。它们可能不是标准的一部分。
If you're using boost::shared_ptr then you can use the various XXX_ptr_cast<>() functions (static_ptr_cast, dynamic_ptr_cast...).
If you're using the MSVC 2010 version I haven't been able to find an implementation of these functions. They may not be part of the standard.
如果shared_ptrs &如果指向的数据不保存在两个客户端共用的内存中(例如,客户端在不同的进程中运行,并且数据不在共享内存中),则来自一个客户端的指针对另一个客户端无效。您需要构建指向数据的表示并传输它。接收者在消息传递层构建自己的数据副本,并将一个shared_ptr传递给客户端。
If the shared_ptrs & pointed-to data aren't held in memory common to both clients (e.g. the clients run in different processes, and the data isn't in shared memory), the pointers from one client won't be valid for the other. You'll need to construct a representation of the pointed-to data and transmit that. The receiver constructs its own copy of the data in the messaging layer and passes a shared_ptr to that up to the client.
如果您计划在客户端之间传递的所有可能的数据类型都继承自某个公共基类,则您可以简单地在基类中包含一个标志变量,该变量指示当前实例是哪种派生类型。在客户端之间传递基类指针,然后使用
dynamic_cast
将基指针向下转换为适当的派生类型。If all possible data types that you plan on passing between clients inherit from some common base class, you can simply include a flag variable in the base class which indicates which derived type the current instance is. Pass base-class pointers between clients, and then use
dynamic_cast
to downcast the base pointer to the appropriate derived type.