Boost serialization multiple objects

久未见 提交于 2019-12-12 11:59:07

问题


Im trying to build a persistence module and Im thinking in serialize/deserialize the class that I need to make persistence to a file. Is possible with Boost serialization to write multiple objects into the same file? how can I read or loop through entrys in the file? Google protocol buffers could be better for me if a good performance is a condition?


回答1:


A Serialization library wouldn't be very useful if it couldn't serialize multiple objects. You can find all the answers if you read their very extensive documentation.




回答2:


I am learning boost, and I think you can use boost serialization as a log file and keep adding values using your logic. I faced the same problem, and if I'm not wrong your code was something like this :

#include <iostream>
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

int main()  {
    int two=2;

    for(int i=0;i<10;i++)   {

        std::ofstream ofs("table.txt");
        boost::archive::text_oarchive om(ofs);
        om << two;
        two = two+30;
        std::cout<<"\n"<<two;
    }

    return 0;
}

Here when you close the braces (braces of the loop), the serialization file closes. And you may see only one value written in table.txt , if you want to store multiple values, your code should be something like this:

#include <iostream>
#include <fstream>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

int main()  {
    int two=2;

    {
        std::ofstream ofs("table.txt");
        boost::archive::text_oarchive om(ofs);
        for(int i=0;i<10;i++)   {

            om << two;
            two = two+30;
            std::cout<<"\n"<<two;
        }
    }

    return 0;
}

Here you can see that the braces enclosing boost::serialization::text_oarchive closes only when I'm done with serialization of the result of my logic.



来源:https://stackoverflow.com/questions/3870123/boost-serialization-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!