是否可以在共享内存中存储多态类? [英] Is it possible to store polymorphic class in shared memory?

查看:166
本文介绍了是否可以在共享内存中存储多态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有类BaseDerived : public Base. 我已经使用boost :: interprocess库构造了一个共享内存段.是否可能具有与此类似的代码:

Suppose I have class Base and Derived : public Base. I have constructed a shared memory segment using boost::interprocess library. Is it possible to have code similar to this:

Base* b = new Derived(); 
write(b); //one app writes
Base* b2 = read(b); //second app reads
//b equals b2 (bitwise, not the ptr location)

例如,我在这里看到的问题是Base的派生类所需的空间未知(因此要分配多少shmem?)

The problems I see here is for instance that the required space for a derived class of Base is unknown (so how much shmem to allocate?)

:如何在应用程序之间通过指针传递对象?

Q: how to pass objects via pointers between applications?

推荐答案

只需阅读其尤其是:

禁止虚拟化

Virtuality forbidden

虚拟表指针和虚拟表在地址中 构造对象的过程的空间,所以如果我们放置一个 具有虚拟功能的类或虚拟基类, 放置在共享内存中的指针将对其他进程无效 他们会崩溃.

The virtual table pointer and the virtual table are in the address space of the process that constructs the object, so if we place a class with a virtual function or virtual base class, the virtual pointer placed in shared memory will be invalid for other processes and they will crash.

这个问题很难解决,因为每个过程都需要一个 不同的虚拟表指针和包含该指针的对象 指针在许多进程之间共享.即使我们映射了映射 在每个进程中位于同一地址的区域中,虚拟表可以 在每个过程中使用不同的地址.启用虚拟功能 对于进程之间共享的对象,需要对编译器进行深层更改 虚拟功能会遭受性能损失.这就是为什么 Boost.Interprocess没有任何计划支持虚拟功能 和进程之间共享的映射区域中的虚拟继承.

This problem is very difficult to solve, since each process needs a different virtual table pointer and the object that contains that pointer is shared across many processes. Even if we map the mapped region in the same address in every process, the virtual table can be in a different address in every process. To enable virtual functions for objects shared between processes, deep compiler changes are needed and virtual functions would suffer a performance hit. That's why Boost.Interprocess does not have any plan to support virtual function and virtual inheritance in mapped regions shared between processes.

这篇关于是否可以在共享内存中存储多态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆