简体   繁体   English

boost serialize和std :: shared_ptr

[英]boost serialize and std::shared_ptr

I Have a object which the following field : 我有一个以下领域的对象:

boost::unordered_map<std::string, std::shared_ptr<Foo> > m_liste_;

I would like to serialize it, but it seems std::shared_ptr can't be serialized in a simple manner 我想序列化它,但似乎std :: shared_ptr无法以简单的方式序列化

anyone have a solution ? 谁有解决方案?

I suspect you are missing an include, 我怀疑你错过了一个包含,

#include <boost/serialization/shared_ptr.hpp>

link, at the bottom 链接,在底部

Also, the example makes it look like aliasing and cycles are taken care of by default. 此外,该示例使其看起来像混叠,并且默认情况下会处理循环。

_Of course, having cycles will lead to potential memory leaks with shared_ptr that have nothing to do with serialization, and you'll still have to heed those (by avoiding cycles or judicious use of weak_ptr)_ _当然,拥有循环会导致shared_ptr潜在的内存泄漏与序列化无关,你仍然需要注意那些(通过避免循环或明智地使用weak_ptr)_

See also: 也可以看看:

Unfortunately the answer is that there isn't a simple way to serialise anything with pointers in it, because the memory layout of your data is likely to be different when you load it back in. A serialiser capable of dealing with pointers would need to be very smart, and come up with a 'memory layout' to save to disc that had valid pointer addresses in it for the stored structure, and which then rewrote them as the structure was deserialised in order to get the pointers pointing to the right places after loading is complete. 不幸的是,答案是没有一种简单的方法可以将任何指针串行化,因为当你重新加载数据时,你的数据的内存布局可能会有所不同。一个能够处理指针的串行器需要是非常聪明,并提出一个'内存布局'来保存到存储结构中有有效指针地址的光盘,然后在结构被反序列化时重写它们,以便指针指向正确的位置之后加载完成。

The really fun part is that if you allow pointers in serialisable structures you have to be able to cope with cyclic reference graphs. 真正有趣的部分是,如果你允许可串行结构中的指针,你必须能够处理循环参考图。 Also, shared_ptr keeps internal reference counts and accounting information so that it knows when to destroy an object, so the serialiser would need to know all about how that works as well, in order to correctly record reference counts (and ignore references from shared_ptr objects which aren't inside the serialised tree but do point to thinks inside it). 此外, shared_ptr保留内部引用计数和记帐信息,以便它知道何时销毁对象,因此序列化程序需要知道所有这些如何工作,以便正确记录引用计数(并忽略来自shared_ptr对象的引用)不是在序列化的树内,而是指向内部思考)。

Basically it's a giant headache, and that's why serialisation libraries don't do it by default. 基本上它是一个巨大的头痛,这就是为什么序列化库默认不这样做的原因。 You usually end up needing quite specific custom behaviour if you want to do it, so they leave it up to you to implement that in order to ensure it's done correctly. 如果你想这样做,你通常最终需要非常具体的自定义行为,因此他们会让你实现它以确保它正确完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM