Question

"Whenever we call serialization on a pointer (or reference), this triggers the serialization of the object it points to (or refers to) whenever necessary" - A practical guide to C++ serialization at codeproject.com This article has a nice explanation to demonstrate how serializing a pointer also serializes the data pointed to by the pointer, so I wrote a code to try this :

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

after running this code, i opened file.txt and found a hexadecimal pointer address and not the values pointed to by this address, i wrote a deserialization code too:

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;

and i got segmentation fault here! Can anyone tell me how to get this working? thanks a lot!

Was it helpful?

Solution

You wrote the object to the stream, not the archive :)

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

Try

    def << point_first;

instead. Result:

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

See it Live (with deserialization) On Coliru

OTHER TIPS

You need to write (using operator<<) the pointer into the archive, not the file. Your code should be:

std::ofstream abc("file.txt");
{
    boost::archive::text_oarchive def(abc);
    def << point_first;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top