Hi,
I sometimes use shared_ptr<const X> to share read-only resources between
different classes.
However serializing shared_ptr<const X> causes problems as shown in the
attached code.
Saving is no problem, but loading fails to compile with an error about
converting from const to non-const.
I managed to make it compile and run by splitting serialize into load/save.
Save is as before, but in load I deserialize into a shared_ptr<X> (no const)
and just assign that to the const version.
Is this the preferred way? It seems like a hack since I'm saving as one
type and loading as another, albeit closely related, type.
Thanks.
-- Anders
#include
#include
#include
#include
#include <fstream>
class B
{
public:
int x;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(x);
}
};
class A
{
public:
boost::shared_ptr<const B> bar;
friend class boost::serialization::access;
//This doesn't work..
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(bar);
}
/*
//This works..
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
boost::shared_ptr<B> tmp;
ar & BOOST_SERIALIZATION_NVP(tmp);
bar = tmp;
}
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
ar & BOOST_SERIALIZATION_NVP(bar);
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
*/
};
int main(int argc, const char* argv[])
{
{
boost::shared_ptr<B> b(new B);
b->x = 17;
A a = { b };
std::ofstream ofs("test.xml");
boost::archive::xml_oarchive oa(ofs);
oa << BOOST_SERIALIZATION_NVP(a);
}
{
A a;
std::ifstream ifs("test.xml");
boost::archive::xml_iarchive ia(ifs);
ia >> BOOST_SERIALIZATION_NVP(a);
}
}