【问题标题】:Boost serialization of pointer saves hexadecimal value of pointer not the contents of the object指针的Boost序列化保存指针的十六进制值而不是对象的内容
【发布时间】:2014-02-21 10:05:05
【问题描述】:

“每当我们在指针(或引用)上调用序列化时,它都会在必要时触发它指向(或引用)的对象的序列化” - A practical guide to C++ serialization at codeproject.com文章有一个很好的解释来演示如何序列化指针也序列化指针指向的数据,所以我写了一个代码来试试这个:

#include <fstream>
#include <iostream>

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

class datta {
public:
    int integers;
    float decimals;

    datta(){}
    ~datta(){}

    datta(int a, float b)   {
        integers=a;
        decimals=b;
    }

    void disp_datta()   {

        std::cout<<"\n int: "<<integers<<" float" <<decimals<<std::endl;

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

int main()  {

    datta first(20,12.56);
    datta get;
    datta* point_first;
    datta* point_get;

    point_first=&first;

    first.disp_datta();
    std::cout<<"\n ptr to first :"<<point_first;

//Serialize

    std::ofstream abc("file.txt");
    {
        boost::archive::text_oarchive def(abc);
        abc << point_first;
    }

return 0;
}

运行这段代码后,我打开file.txt,发现一个十六进制的指针地址而不是这个地址所指向的值,我也写了一个反序列化代码:

std::ifstream zxc("file.txt");
{
    boost::archive::text_iarchive ngh(zxc);
    ngh >> point_get;
}

//Dereference the ptr and

get = *point_get;

get.disp_datta();
std::cout<<"\n ptr to first :"<<point_get;

我在这里遇到了分段错误!谁能告诉我如何让这个工作?非常感谢!

【问题讨论】:

    标签: c++ class boost boost-serialization


    【解决方案1】:

    您将对象写入流,而不是存档:)

        boost::archive::text_oarchive def(abc);
        abc << point_first;
    

    试试

        def << point_first;
    

    相反。结果:

    22 serialization::archive 10 0 1 0
    0 20 12.56
    

    Live (with deserialization) On Coliru

    【讨论】:

    • 指针反序列化是否需要使用-lboost_system标志?
    • 终于成功运行了。非常感谢!恢复对人类(或计算)的信心!
    【解决方案2】:

    您需要(使用运算符

    std::ofstream abc("file.txt");
    {
        boost::archive::text_oarchive def(abc);
        def << point_first;
    }
    

    【讨论】:

    • 这个答案究竟是如何增加我在此之前 30 分钟发布的见解?
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多