Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Created November 23, 2013 14:14
Show Gist options
  • Save nekko1119/7615042 to your computer and use it in GitHub Desktop.
Save nekko1119/7615042 to your computer and use it in GitHub Desktop.
Boost.Serializationの使い方を理解するために書いたサンプル
#include <iostream>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
class Hoge
{
public:
Hoge(int d, double& r) : data_(d), ref_(r) {}
int data() const { return data_; }
double const& ref() const { return ref_; }
private:
int data_;
double& ref_;
};
namespace boost
{
namespace serialization
{
template <typename Archive>
void serialize(Archive& ar, Hoge& hoge, unsigned int ver)
{
std::cout << "serialize\n";
boost::serialization::split_free(ar, hoge, ver);
}
template <typename Archive>
void save(Archive&, Hoge const&, unsigned int)
{
std::cout << "save\n";
}
template <typename Archive>
void load(Archive&, Hoge&, unsigned int)
{
std::cout << "load\n";
}
template <typename Archive>
void save_construct_data(Archive& ar, Hoge const* p, unsigned int)
{
std::cout << "save_construct_data\n";
auto const& d = p->data();// ar << xxxや、make_nvpは左辺値参照を引数に取るので、右辺値を左辺値に変換する必要が有る
ar << boost::serialization::make_nvp("data", d);
ar << boost::serialization::make_nvp("ref", p->ref());
}
template <typename Archive>
void load_construct_data(Archive& ar, Hoge* p, unsigned int)
{
std::cout << "load_construct_data\n";
int d;
double* r = new double{};// ここで確保したメモリは手動で開放する必要があるので、shared_ptrとか使ったほうがいい
ar >> boost::serialization::make_nvp("data", d);
ar >> boost::serialization::make_nvp("ref", *r);
::new(p) Hoge(d, *r);
}
}
}
#include <fstream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
int main()
{
{
double r = 3.14;
Hoge h{42, r};
auto* p = &h;
std::ofstream ofs{"hoge.xml"};
std::cout << "xml_orchive\n";
boost::archive::xml_oarchive oa{ofs};
std::cout << "make_nvp\n";
oa << boost::serialization::make_nvp("Hoge", p);
std::cout << "-----------------------\n";
}
{
Hoge* p = nullptr;
std::ifstream ifs{"hoge.xml"};
std::cout << "xml_iarchive\n";
boost::archive::xml_iarchive ia{ifs};
std::cout << "make_nvp\n";
ia >> boost::serialization::make_nvp("Hoge", p);
std::cout << p->data() << ", " << p->ref() << std::endl;
delete &(p->ref());// load_construct_dataで確保したメモリを開放する
delete p;
std::cout << "-----------------------\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment