利用boost的serialization库实现c++对象的序列化与反序列化

来源:互联网 发布:最好的看书软件 编辑:程序博客网 时间:2024/05/16 19:09
代码示例及讲解

#include <cstddef>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/string.hpp>//本例中需要对string进行存储,所以引入string.hpp;此外还有一些预定义的模板,如vector、list、map等
#include <boost/serialization/access.hpp>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Cat{
    public:
        Cat() {}//每个对象都必须提供一个默认构造函数
        Cat(string name) { this->name = name; }
        void print() { cout<<"my name is "<<this->name<<endl; }
        string getName() { return this->name; }
        void setName(string name) { this->name = name; }
    private:
        friend class boost::serialization::access;
        template<class Archive>
            void serialize(Archive & ar, const unsigned int version){
                ar & name;
            }
        string name;
};


class CatPtr{
    public:
        CatPtr() : c(0)  {}
        CatPtr(Cat c) : c(c) {}
        void print() { cout<<"the cat pointed to is "<<c->getName()<<endl; }
    private:
        Cat *c;
        friend class boost::serialization::access;
        template<class Archive>
            void serialize(Archive & ar, const unsigned int version){
                ar.register_type(static_cast<Cat *>(NULL));//本例中是通过Cat类的指针来使Cat对象序列化的,所以需要对该指针进行注册
                ar & c;
            }
};

template <class T>
void save(const T &c, string filename){
    ofstream ofs(filename.c_str(),ios::app);
    boost::archive::text_oarchive oa(ofs);
    oa & c;
}

template <class T>
void restore(T &c, string filename){
    ifstream ifs(filename.c_str());
    boost::archive::text_iarchive ia(ifs);
    ia & c;
}


int main(){
    Cat c("Kitty");
    string filename = "test.txt";
    cout<<"original cat:"<<endl;
    c.print();
    save(c,filename);
    Cat nc;
    restore(nc,filename);
    cout<<"new cat:"<<endl;
    nc.print();


    Cat *c1 = new Cat("Ann");
    CatPtr cp(c1);
    cp.print();
    string filename = "0test.txt";
    save(cp,filename);
    CatPtr ncp;
    restore(ncp,filename);
    ncp.print();
    return 0;
}


参考

http://www.boost.org/doc/libs/1_54_0/libs/serialization/doc/tutorial.html

http://www.ibm.com/developerworks/cn/aix/library/au-boostserialization/

原创粉丝点击