Posts Tagged ‘boost’

Serializing non-default-constructible objects with boost

November 18, 2008

Boost serialization is not trivial for an object that has no default constructor. Consider this:

class Foo
{
public:
	int v1;
	int v2;

	Foo(int v1_) { v1 = v1_; }

	template <typename Archive>
	void serialize(Archive& ar, unsigned int version)
	{
		ar & v1;
		ar & v2;
	}
};

//...
binary_iarchive ar;
Foo foo(0);
ar >> foo;

We only suffer a minor inelegance because of redundantly initializing foo. But what if we need to deserialize a pointer?
Hint: it won’t compile