robogos
robogos

Reputation: 131

Boost deserialisation error

I am trying to serialise/deserialise a simple object. I am able to serialise it:

#include <vector>
   #include <sstream>
   #include <boost/archive/text_oarchive.hpp>
   #include <boost/archive/text_iarchive.hpp>
   #include <boost/serialization/vector.hpp>


   class DataClass{
       public:
           std::vector<std::string> data;

           DataClass(){}
           ~DataClass(){}

           friend class boost::serialization::access;
           template<typename Archive>
               void serialize(Archive & ar, const unsigned int version) const{
                   ar & data;
               }   
   };

   int main(){
       using std::cout;
       using std::endl;
       using std::string;

       DataClass data_obj;
       data_obj.data.push_back("some data 1");
       data_obj.data.push_back("some data 2");

       std::ostringstream archive_stream;
       boost::archive::text_oarchive archive(archive_stream);
       archive << data_obj;
       string str_data_to_send = archive_stream.str();
       const char* data_to_send = archive_stream.str().c_str();


       std::istringstream archive_stream2(data_to_send);

       boost::archive::text_iarchive archive2(archive_stream2);
       DataClass received_data_obj;
       //archive2 >> received_data_obj;

   }

I receive an error if I uncomment the last statement

archive2 >> received_data_obj;

In file included from /opt/local/include/boost/archive/text_oarchive.hpp:31:
In file included from /opt/local/include/boost/archive/basic_text_oarchive.hpp:32:
In file included from /opt/local/include/boost/archive/detail/common_oarchive.hpp:22:
In file included from /opt/local/include/boost/archive/detail/interface_oarchive.hpp:23:
In file included from /opt/local/include/boost/archive/detail/oserializer.hpp:67:
/opt/local/include/boost/archive/detail/check.hpp:162:5: error: static_assert failed "typex::value"
    BOOST_STATIC_ASSERT(typex::value);
    ^                   ~~~~~~~~~~~~

I can not post the whole error message because my post will be "mostly code".

Upvotes: 2

Views: 850

Answers (1)

Igor R.
Igor R.

Reputation: 15085

Go to the source code, where static assert occurred, and you'll see the comments that explain the issue:

// cannot load data into a "const" object unless it's a
// wrapper around some other non-const object.

This happens because you defined serialization member function as const, so data member is also const when being accessed within serialization function.

Upvotes: 4

Related Questions