How do I make Boost serialization work with std::shared_ptr?
This question has been asked here and a few other places but the answers
don't really seem to address Boost 1.54, which is supposed to support
std::shared_ptr. To illustrate the issue, suppose we want to serialize a
class containing a vector of shared pointers, along with a static load
function that will build the class and a save function that will store the
instance to file, and suppose that we can't just use the serialize member
function for whatever reason (this particular example doesn't really
illustrate such a case but in my code I can't use the serialize member
function so this example doesn't use it either):
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <fstream>
#include <memory>
#include <vector>
class A
{
public:
std::vector<std::shared_ptr<int>> v;
void A::Save(char * const filename);
static A * const Load(char * const filename);
//////////////////////////////////
// Boost Serialization:
//
private:
friend class boost::serialization::access;
template<class Archive> void serialize(Archive & ar, const
unsigned int file_version) {}
};
// save the world to a file:
void A::Save(char * const filename)
{
// create and open a character archive for output
std::ofstream ofs(filename);
// save data to archive
{
boost::archive::text_oarchive oa(ofs);
// write the pointer to file
oa << this;
}
}
// load world from file
A * const A::Load(char * const filename)
{
A * a;
// create and open an archive for input
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);
// read class pointer from archive
ia >> a;
return a;
}
namespace boost
{
namespace serialization
{
template<class Archive>
inline void save_construct_data(
Archive & ar, A const * t, unsigned const int file_version
)
{
ar << t->v;
}
template<class Archive>
inline void load_construct_data(
Archive & ar, A * t, const unsigned int file_version
)
{
ar >> t->v;
}
}
}
int main()
{
}
The above code generates a long list of errors starting with
c:\local\boost_1_54_0\boost\serialization\access.hpp(118): error C2039:
'serialize' : is not a member of 'std::shared_ptr<_Ty>', which as far as I
understand shouldn't be true given that I have loaded the boost shared_ptr
serialization library which ostensibly supports std::shared_ptr. What am I
missing here?
No comments:
Post a Comment