如果没有默认构造函数,则禁止直接序列化对象(而不是通过指针)

时间:2016-02-29 15:59:41

标签: c++ boost boost-serialization

当我需要在没有默认构造函数的情况下序列化对象时,我最近一直在使用save_construct_data()load_construct_data()。因为它没有意义:

MyObject a; // can't do this because there is no default constructor
archive >> a;

我们必须这样做:

MyObject* aPointer;
archive >> a;

load_construct_data()之前调用serialize()。但是,当然只有在使用save_constructor_data()对象进行序列化时才会有效,只有当它被写为指针时才会被调用,例如。

MyObject a(1,2);
MyObject aPointer = &a;
archive << aPointer;

这一切都运行正常,但似乎archive << a;工作正常,但逻辑上没有意义,因为它永远无法反序列化。有没有办法禁止这个调用,以便对象(可能是较大类的类成员等)不会意外地通过指针写入Object?

-------------编辑----------

试图遵循SergeyA的建议,我做了以下演示。不幸的是,它似乎没有正确读取数据?

#include <fstream>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>

class Point
{
private:
    friend class boost::serialization::access;

    template<class TArchive>
    void serialize(TArchive& archive, const unsigned int version)
    {
        archive & mX;
        archive & mY;
    }

public:
    template<class TArchive>
    Point(TArchive& archive)
    {
        serialize(archive, 0);
    }

    Point(){} // Only provided to test Works()

    Point(const float x, const float y) : mX(x), mY(y) { }

    float mX = 4;
    float mY = 5;
};

void Works()
{
    std::cout << "Works():" << std::endl;
    Point p(1,2);

    std::ofstream outputStream("test.archive");
    boost::archive::text_oarchive outputArchive(outputStream);
    outputArchive << p;
    outputStream.close();

    // read from a text archive
    std::ifstream inputStream("test.archive");
    boost::archive::text_iarchive inputArchive(inputStream);
    Point pointRead;
    inputArchive >> pointRead;

    std::cout << pointRead.mX << " " << pointRead.mY << std::endl;
}

void DoesntWork()
{
    std::cout << "DoesntWork():" << std::endl;
    Point p(1,2);

    std::ofstream outputStream("test.archive");
    boost::archive::text_oarchive outputArchive(outputStream);
    outputArchive << p;
    outputStream.close();

    std::ifstream inputStream("test.archive");
    boost::archive::text_iarchive inputArchive(inputStream);
    Point pointRead(inputArchive);

    std::cout << pointRead.mX << " " << pointRead.mY << std::endl;
}

int main()
{
    Works(); // Output "1 2"
    DoesntWork(); // Output "0 0"
    return 0;
}

0 个答案:

没有答案