Nominate our 2022 Qt Champions!

Serializing QVector of pointers

  • Hi,

    I'm not sure that this is a full question of Qt, but I don't know where to ask, so I am here !

    I have a QVector of objects, referenced by pointers. It is so a QVector of pointers.
    I want to serialize my class containing this QVector. I overloaded the operators << and >>, and the serializing is working for the most of my attributes.
    However, the serializing of my QVector is not working. I bet I have to serialize all the objects inside the QVector and rebuilt it in output, but I don't know how to do that. I bet I should do a deep copy of the QVector, but don't know how to proceed inside my operator << or >>.
    When I use the >> or << operator for my QVector, it serializes just the reference, and not the objects. How can I do that ?

    Thanks by advance

  • If you have a << and >> for your class, which is in QVector then you could write function like this:
    // PSEUDOCODE - not working
    for (int i = 0; i < vector.size(); ++i)
    output << *( i ) );

  • Did you implement operator<< and operator>> for the pointer type of your type?

    QDataStream& operator<<(QDataStream& s, const YourType *yt);
    QDataStream& operator>>(QDataStream& s, YourType *yt);

    And don't forget to make operator<< a friend of your class, otherwise you cannot access the private members you want to serialize.

  • I would start looking into other solutions as well. Boost::serialize for instance can serialize pointers to objects, and makes sure that you don't serialize the same object more than one time.

Log in to reply