序列化和反序列化提升共享指针

Serialize and deserialize boost shared pointers

我知道有机会使用 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
}

} }

现在我想以同样的方式处理反序列化。所以,我想获取序列化密钥并在某个地图中获取对象。

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

一个可能的解决方案就在我的脑海中:

如何使用 actual 映射(例如 std::unordered_map)将原始指针映射到对象?别忘了对地图进行序列化。

然后在反序列化的时候,先对map进行反序列化,然后使用序列化后的指针从map中获取对象

在我看来,您可能只是 "optimizing" 避免重复的序列化对象。

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 实例 :别名指针被存档跟踪并且只被(反)序列化一次。

¹ 并在一些帮助下作为参考