0

I need serialize a class with fields: int, pointer to int, array, class object, pointer to class object, reference to class object, pointer to class object with virtual parent.

I tried to implement it. I managed to do for int and array. But I can not deal with pointers and references

class B() {};

class Person
{
 public:
int age; // work
    int *ageptr = &age; // not work
std::vector<int> favoriteNumbers; //work

    B b; // not work
    B *bptr = &b; // not work
    B &bref = b; // not work

Person();
~Person();

private:
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive &ar, const unsigned int version) {
        ar &BOOST_SERIALIZATION_NVP(age);
        ar &BOOST_SERIALIZATION_NVP(ageptr); // error
        ar &BOOST_SERIALIZATION_NVP(b); // error
        ar &BOOST_SERIALIZATION_NVP(bptr); // error
        ar &BOOST_SERIALIZATION_NVP(bref); // error
        ar &BOOST_SERIALIZATION_NVP(favoriteNumbers);
    }
};
Vitalja B.
  • 11
  • 6

1 Answers1

0

In your particular case, since the references and pointers refer to member variables, they do not need to be serialized/deserialized. The constructor already set these members to correct values.

With regards to serializing pointers read Pointers section of serialization tutorial.

You cannot deserialize references in general, though, because they are aliases to other objects and they cannot be reassigned to refer to another object. Also, taking address and sizeof of a reference returns those of the object being referred. I would also recommend against using reference members at all.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271