序列化和反序列化boost共享指针

时间:2018-07-14 16:30:39

标签: c++ boost shared-ptr boost-serialization

我知道有机会使用boost创建的方法来序列化共享指针,但是我创建了这个:

namespace boost { namespace serialization {

template<class Archive, class T>
inline void serialize(Archive& ar, boost::shared_ptr<T>& b, const unsigned int file_version)
{
    // serialize a string which is the key of the pointer
}

} }

现在,我想以相同的方式处理反序列化。因此,我想使用序列化的密钥并在某些映射中获取对象。

如何在反序列化中处理此问题?

2 个答案:

答案 0 :(得分:2)

一个可能的解决方案只是我的脑海:

使用 actual 映射(例如std::unordered_map)将原始指针映射到对象怎么样?别忘了还要序列化地图。

然后在反序列化时,首先对地图进行反序列化,然后使用序列化的指针从地图中获取对象。

答案 1 :(得分:2)

在我看来,您可能只是在“优化”以避免重复的序列化对象。

Boost序列化已经为(智能)指针内置了此功能¹:Object Tracking

以下是对样品的含义演示:

Live On Coliru

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/unordered_map.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/vector.hpp>
#include <iostream>

struct HeyHey {

    std::string name;
    HeyHey(std::string n = "") : name(n) {}

  private:
    friend class boost::serialization::access;
    template <typename Ar> void serialize(Ar& ar, unsigned) { ar & name; }
};

using HeyPtr = std::shared_ptr<HeyHey>;

int main() {

    std::stringstream ss;

    {
        std::vector<HeyPtr> ptrs = { 
            std::make_shared<HeyHey>("one"),
            std::make_shared<HeyHey>("two"),
            std::make_shared<HeyHey>("three"),
            std::make_shared<HeyHey>("four"),
        };

        std::unordered_map<int, HeyPtr> m = {
            { 1, ptrs[0] },
            { 2, ptrs[1] },
            { 3, ptrs[2] },
            { 4, ptrs[3] },
        };

        boost::archive::text_oarchive oa(ss);
        oa << ptrs << m;
    }

    {
        std::vector<HeyPtr> ptrs;
        std::unordered_map<int, HeyPtr> m;

        boost::archive::text_iarchive ia(ss);
        ia >> ptrs >> m;

        std::cout << "Deserialized:\n";
        for (auto p : m) {
            std::cout << "Key: " << p.first << " mapped to " << std::quoted(p.second->name) << " at address " << p.second.get() << "\n";
        }

        std::cout << "Vector contains: ";
        for (auto sp: ptrs)
            std::cout << sp.get() << " ";

        std::cout << "\n";
    }

}

打印:

Deserialized:
Key: 1 mapped to "one" at address 0x25de420
Key: 2 mapped to "two" at address 0x25de450
Key: 3 mapped to "three" at address 0x25de4b0
Key: 4 mapped to "four" at address 0x25de480
Vector contains: 0x25de420 0x25de450 0x25de4b0 0x25de480 

请注意,地图和向量如何指向相同的HeyHey实例:别名指针已由档案跟踪,并且仅被序列化(反序列化)一次。

¹,并在一些帮助下供参考