Boost反序列化错误

Posted

技术标签:

【中文标题】Boost反序列化错误【英文标题】:Boost deserialisation error 【发布时间】:2014-07-07 01:31:06 【问题描述】:

我正在尝试序列化/反序列化一个简单的对象。 我可以序列化它:

#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;

   

如果我取消注释最后一条语句,我会收到错误

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);
    ^                   ~~~~~~~~~~~~

我无法发布整个错误消息,因为我的帖子将“主要是代码”。

【问题讨论】:

【参考方案1】:

转到发生静态断言的源代码,您将看到解释问题的 cmets:

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

发生这种情况是因为您将serialization 成员函数定义为const,所以data 成员在serialization 函数中被访问时也是const

【讨论】:

以上是关于Boost反序列化错误的主要内容,如果未能解决你的问题,请参考以下文章

c ++ boost将char数组反序列化为obj

使用 Boost 反序列化 Armadillo colvec

boost序列化,原始C数组的反序列化

使用循环序列化和反序列化图形

如何使用 boost std::vector of boost::unordered_map 进行序列化/反序列化

std::vector<float> 成员的 boost 序列化/反序列化失败