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

后端 未结 7 1877
礼貌的吻别
礼貌的吻别 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:36

    This is improvement of denim's solution, which supports loading shared_ptr which points to the same memory, but with different types. This problem can appear when archive contains at the same time shared_ptr and shared_ptr which are pointing to the same object, where A is inherited from B.

    namespace boost {
    namespace serialization {
    
        template
        void save(Archive & archive, const std::shared_ptr & value, const unsigned int /*version*/)
        {
            Type *data = value.get();
            archive << data;
        }
    
        static std::map> hash;
    
        template
        void load(Archive & archive, std::shared_ptr & value, const unsigned int /*version*/)
        {
            Type *data;
            archive >> data;
    
            if (hash[data].expired())
            {
                std::shared_ptr ptr(data);
                value = static_pointer_cast(ptr);
                hash[data] = ptr;
            }
            else value = static_pointer_cast(hash[data].lock());
        }
    
        template
        inline void serialize(Archive & archive, std::shared_ptr & value, const unsigned int version)
        {
            split_free(archive, value, version);
        }
    
    }}
    

    As a weakness of this realization - one massive map.

提交回复
热议问题