使用boost :: serialization将成员为vector <unique_ptr <string >>的成员序列化一个类

时间:2019-08-23 10:31:48

标签: c++ boost boost-serialization

有一个类似的sounding question,但是完全不同,因为它与被序列化的类的unique_ptr的向量有关。 我想有一种方法可以序列化作为矢量的成员。

What I have tried and does not work:

#include<vector>
#include<string>
#include<sstream>
#include<iostream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/forward_list.hpp>
#include <boost/serialization/serialization.hpp>
using namespace boost::archive;
class Person {
    std::vector<std::unique_ptr<std::string>> data_;
    public:
    Person(){
        data_.emplace_back(nullptr);
        data_.emplace_back(new std::string("Bjarne!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"));
    }
    private:
    friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar,const unsigned int)
{
  ar & data_;
}
    public:
    const std::vector<std::unique_ptr<std::string>>& data() const{
        return data_;
    }

};

int main() {
    std::stringstream ss;
    Person p;
    text_oarchive oa{ss};
    oa << p;
    text_iarchive ia{ss};
    Person read;
    ia >> read;
    for (const auto& ptr : read.data()) {
        std::cout << *ptr; 
    }
}

1 个答案:

答案 0 :(得分:1)

就像@CuriouslyRecurringThoughts注释一样,避免在要进行序列化时避免使用std::unique_ptr来表示前哨值,而使用boost::optional代替serialize