Boost序列化指针保存指针的十六进制值而不是对象的内容

时间:2014-02-21 10:05:06

标签: c++ class boost boost-serialization

“每当我们在指针(或引用)上调用序列化时,这会在必要时触发它指向(或引用)的对象的序列化” - 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;

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

2 个答案:

答案 0 :(得分:3)

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

    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

答案 1 :(得分:0)

您需要将(使用operator&lt;&lt;)指针写入存档,而不是文件。你的代码应该是:

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