boost serialize and std::shared_ptr

前端 未结 2 934
轻奢々
轻奢々 2020-12-19 04:09

I Have a object which the following field :

boost::unordered_map > m_liste_;

I would like to

相关标签:
2条回答
  • 2020-12-19 04:44

    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)_

    See also:

    • Template serialization - shared_ptr
    • shared_ptrRevisited
    0 讨论(0)
  • 2020-12-19 04:49

    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).

    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.

    0 讨论(0)
提交回复
热议问题