0
votes

There is a similarly sounding question, but it is totally different because it relates to a vector of unique_ptr of the class that is serialized. I would like to have a way to serialize member that is a vector.

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
Vector of pointers to strings doesn't appear meaningfull. Why not just have a vector of strings? Why would you need the null-pointers? - Aconcagua
It is an example, It could be a pointer to move only UDT - NoSenseEtAl
std::unique_ptr is move-only as well, so that wouldn't be the argument... Still accepted, though, as you'd need pointers for polymorphic types (well, pointer vs. value issue, the null-pointers are another matter!). - Aconcagua
you are right, better example would be a pointer to a type that does not have efficient move, like large std::array or some antique 3rd party code class. - NoSenseEtAl
Best example a polymorphic type, as you cannot do any differently than storing pointers, as you'd suffer from object slicing otherwise ;) - Aconcagua

1 Answers

1
votes

As @CuriouslyRecurringThoughts comments, steer clear of using std::unique_ptrs for sentinel no-values when you want to serialize, use boost::optional instead to serialize.