I have recently been using save_construct_data()
and load_construct_data()
when I need to serialize an object without a default constructor. Since it doesn't make sense to do:
MyObject a; // can't do this because there is no default constructor
archive >> a;
we must do:
MyObject* aPointer;
archive >> a;
which calls load_construct_data()
before serialize()
. However, of course this only works if the object was serialized using save_constructor_data()
which is only called if it is written as a pointer, e.g.
MyObject a(1,2);
MyObject aPointer = &a;
archive << aPointer;
This is all working fine, but it seems like archive << a;
works fine, but logically doesn't make sense, as it will never be able to be deserialized. Is there a way to disallow this call so that objects (perhaps class members of a larger class, etc.) don't accidentally write the Object not through a pointer?
------------- EDIT ----------
Attempting to follow SergeyA's suggestion, I have made the following demo. Unfortunately it does not seem to read the data correctly?
#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;
}