boost::serialization 多态类型初始化
我有一个基类和 4 个派生类。我将所有派生类存储在基类指针类型的向量中。在第一次初始化期间,我使用其构造函数以不同的方式创建每个派生类型。基本上,它们的构造函数中都有不同的参数类型。 (我必须提供一个受保护的默认构造函数来编译 BOOST_CLASS_EXPORT,但这是一个不同的故事)。我不/无法保存这些派生类的所有成员(填充为 ctor)。
现在,当我使用 boost::serialize 从磁盘加载对象时,这些成员(未序列化且特定于每个派生类型)将被销毁。而且,我想不出一种方法来重新初始化这些派生类型,因为我只存储基类指针。
我到底需要的是能够部分加载我的派生类型(指针),而不删除它们的所有内容。
有没有办法克服这个问题,也许是魔法增强定义或函数调用?否则, boost::serialize 的多态性根本不可能。我应该错过一些东西,并希望我能够足够好地定义我的问题。
I have a base class and 4 derived classes. I store all my derived classes in a vector of base class pointer type. During first initialization I create each derived type differently using their constructors. Basically they each have different param types in their ctors. (I had to provide a protected default ctor to make BOOST_CLASS_EXPORT compile but that's a different story). I don't/can't save all the members (filled in ctor) of these derived classes.
Now, when I load objects from the disk using boost::serialize, these members (that are not serialized and specific to each derived type) are destroyed. And, I cannot think of a way to re-initialize these derived types since I only store the base class pointers.
What exactly I need is being able to load my derived types (pointers) partially, without deleting all their content..
Is there a way to overcome this, a magic boost define or function call perhaps? Otherwise, polymorphism with boost::serialize is not possible at all.. I should be missing something and hope I could define my problem good enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要仅仅为了序列化而创建默认构造函数。您可以让 boost 保存/加载非默认构造函数所需的数据,并在加载时使用它来构造新对象。
这样,无论构造函数做什么来确保数据成员的有效性,也可以在序列化期间发生,并且序列化库永远不必直接操作对象的数据成员。这应该可以防止数据被删除。
例如,如果您的类可以使用
name
和size
构建,您可以按如下方式重载函数:查看文档 此处。
You shouldn't need to create a default constructor just for serialization. You can instead have boost save/load the data needed by a non-default constructor, and use that to construct new objects when loading.
That way, whatever your constructors do to ensure the validity of data members can also happen during serialization, and the serialization library never has to manipulate the data members of your objects directly. This should prevent data erasure.
For example, if your class can be constructed using a
name
and asize
, you could overload the functions as follows:Check out the docs here.