How can boost::serialization be used with std::shared_ptr from C++11?

后端 未结 7 1894
礼貌的吻别
礼貌的吻别 2020-12-08 20:23

I know that there is a Boost module for serialization of boost::shared_ptr, but I cannot find anything for std::shared_ptr.

Also, I don\'t know how to implement it e

7条回答
  •  甜味超标
    2020-12-08 20:58

    I finally found a solution on how to serialize the std::shared_ptr using boost serialization. All you need is the following piece of code (explanation follows):

    #include 
    #include 
    
    //---/ Wrapper for std::shared_ptr<> /------------------------------------------
    
    namespace boost { namespace serialization {
    
    template
    void save(Archive & archive, const std::shared_ptr & value, const unsigned int /*version*/)
    {
        Type *data = value.get();
        archive << data;
    }
    
    template
    void load(Archive & archive, std::shared_ptr & value, const unsigned int /*version*/)
    {
        Type *data;
        archive >> data;
    
        typedef std::weak_ptr WeakPtr;
        static boost::unordered_map hash;
    
        if (hash[data].expired())
        {
             value = std::shared_ptr(data);
             hash[data] = value;
        }
        else value = hash[data].lock();
    }
    
    template
    inline void serialize(Archive & archive, std::shared_ptr & value, const unsigned int version)
    {
        split_free(archive, value, version);
    }
    
    }}
    

    This code simply serializes the object managed by the std::shared_ptr in the function save(). If multiple std::shared_ptr instances point to same object boost serialization will take automatically care to store it only once. The magic happens in load() where boost serialization returns a raw pointer to the object (data). This raw pointer is looked up in a hash that holds a weak_ptr for each raw pointer. In case that the weak_ptr in the hash is expired we can safely create a new shared_ptr instance, let it manage the raw pointer and store a weak_ptr in the hash. In case that the weak_ptr is not expired we simply lock it to return a shared_ptr. This way the reference counting is correct.

提交回复
热议问题