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

top*_*dev 2 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

...

// 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
}
Run Code Online (Sandbox Code Playgroud)

Ise*_*ria 5

至于非缺省构造的对象,我建议你看的项目 非默认构造函数 在这里.
你的类可以通过编写自己的函数模板被序列化load_construct_datasave_construct_data.