How to deserialize Vector of int using QDataStream

QVector<int> *l_iVec = new QVector<int>();


QDataStream dataStream;
dataStream<<l_iVec; //successfully build 

dataStream>>l_iVec; //getting error on this line

 error: invalid operands to binary expression ('QDataStream' and 'QVector<int> *') dataStream>>l_iVec;
               ~~~~~~~~~~^ ~~~~~~

I am trying to deserialize vector using qdatastream but get following error and unable to see the problem of error.It is serialize successfully with no error.

1 answer

  • answered 2018-01-14 07:12 dtech

    First of all:

    QVector<int> *l_iVec = new QVector<int>();

    There is no good reason to allocate QVector dynamically, it is already a tiny wrapper to dynamically allocated data. You can return it by value efficiently, as the operation will not involve a deep copy. For situations you need to pass by reference, use a reference and not a pointer.

    Secondly, as a result of your odd choice of allocation, you are currently not serializing and deserializing the vector data, but the value of the pointer to it. Dereference the pointer at the very least, or better off, don't use a pointer in the first place.

    QDataStream &   operator<<(QDataStream &out, const QVector<T> &vector)
    QDataStream &   operator>>(QDataStream &in, QVector<T> &vector)

    As you see, the data stream operators take in a vector reference, not a vector pointer, and if your current serialization "works" that's probably a case of conversion, where the pointer is treated like an integer.