使用引用反序列化对象,没有默认构造函数(boost :: serialization)

时间:2011-02-08 19:37:45

标签: c++ serialization boost reference default-constructor

boost :: serialization库中是否可以使用引用反序列化(多态)对象而没有默认构造函数?

class Example
{
    int& value;

public:

    Example(int _value): value(_value) {}
    virtual ~Example() {}

    friend class boost::serialization::access;
    template<typename Archive>
    void serialize(Archive & ar, const unsigned int file_version)
    {
        ar & value;
    }
};

class Usage
{
    Example* example;

public:

    Usage(): example(new Example(123)) {}
    ~Usage() { delete example; }

    friend class boost::serialization::access;
    template<typename Archive>
    void serialize(Archive & ar, const unsigned int file_version)
    {
        ar & example;
    }
};

...

// serialize and deserialize object with reference and no default constructor
{
    Usage source;

    std::ostringstream oss;
    boost::archive::text_oarchive oa(oss);
    oa & source;

    Usage target;

    std::istringstream iss(oss.str());
    boost::archive::text_iarchive ia(iss);
    ia & target; // does not compile
}

1 个答案:

答案 0 :(得分:5)

对于非默认的可构造对象,我建议查看该项目 非默认构造函数 here
您的课程可以序列化 编写自己的功能模板load_construct_datasave_construct_data