I am trying to serialize a singleton class with pointer.
boost.serialization is a good tools. it can work well if there is no pointer member variable.
once include pointer, read it back will crased.
here is my code:
#include <fstream>
#include <iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/unordered_map.hpp>
using namespace std;
class gps_position {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & degrees;
ar & minutes;
ar & seconds;
ar & v;
ar & mm;
}
int degrees;
int minutes;
float seconds;
std::vector<double> v;
std::unordered_map<std::string, std::unordered_map<std::string, double>> mm;
std::unordered_map<int, int*> test; // here stores pointers. if without it, can work well
private:
gps_position(){};
gps_position(int d, int m, float s, double a, double b, double c) : degrees(d), minutes(m), seconds(s) {
v.push_back(a);
v.push_back(b);
v.push_back(c);
mm["a"]["a"] = c;
int* aa = new int(3);
test[1] = aa;
}
public:
static gps_position& Inst(int d, int m, float s, double a, double b, double c) { static gps_position g(d, m, s, a,b,c); return g;}
static gps_position& Inst() { static gps_position g; return g;}
void print() const {
std::cout << degrees << " " << seconds << endl;
cout << "start vector:";
for (const auto & i : v) cout << i << endl;
cout << "end vector\n";
for (auto & i : mm) cout << i.first << "=" << i.second.at("a") << endl;
cout << "test[1] = " << *(test.at(1)) << endl;
}
};
void write() {
std::ofstream ofs("a");
const gps_position& g = gps_position::Inst(35, 59, 24.567f, 1.2, 3.6, 9.1);
boost::archive::text_oarchive oa(ofs);
g.print();
oa << g;
}
void read() {
std::ifstream ifs("a");
boost::archive::text_iarchive ia(ifs);
gps_position& g = gps_position::Inst();
ia >> g;
g.print(); // crashed because print failed in pointer.
}
int main() {
write();
read();
}
could you help me on this? how to serialize a class with pointer member variable?