简体   繁体   中英

QVector vs std::vector for complex types

So I have a structure:

struct Alarm{
    Alarm(QString operation, double comparison, QString text, quint8 color):
        operation(operation), comparison(comparison), text(text), color(color){}

    int             element;
    QString         operation;
    double          comparison;

    QString         text;
    quint8          color;

    QDateTime       riseTime;
};

Note that it doesn't have a default constructor Alarm() . I would like to have a vector container of objects of this structure. If I try to use QVector the code fails to compile in the code where I attempt to append new object with this error:

/usr/include/x86_64-linux-gnu/qt5/QtCore/qvector.h: In instantiation of ‘void QVector<T>::defaultConstruct(T*, T*) [with T = Alarm]’:
/usr/include/x86_64-linux-gnu/qt5/QtCore/qvector.h:580:41:   required from ‘void QVector<T>::reallocData(int, int, QArrayData::AllocationOptions) [with T = Alarm; QArrayData::AllocationOptions = QFlags<QArrayData::AllocationOption>]’
/usr/include/x86_64-linux-gnu/qt5/QtCore/qvector.h:654:20:   required from ‘void QVector<T>::append(const T&) [with T = Alarm]’
/usr/include/x86_64-linux-gnu/qt5/QtCore/qvector.h:280:13:   required from ‘QVector<T>& QVector<T>::operator<<(const T&) [with T = Alarm]’
/opt/buildagent/work/1a89dfc8903ef3d7/ground/gcs/src/plugins/qmlview/Alarms.cpp:56:243:   required from here
/usr/include/x86_64-linux-gnu/qt5/QtCore/qvector.h:322:13: error: no matching function for call to ‘Alarm::Alarm()’
          new (from++) T();

It appears that QVector requires the class it holds to have a default constructor. However, using std::vector<T> compiles just fine.

My question is why? Is this a requirement for using QVector to have a class with default constructor? Or I'm not using the container correctly?

The reason why std::vector works differently lies in the fact that in vector, raw uninitialized memory is allocated and then calls copy constructor to do the copy whenever required. This process doesn't require calling default constructor for resize(). That's why there is no dependency as such on default constructor.

On the other hand,QVector requires type to be default constructible because of the way the internal function realloc() is implemented.

according to the QT docs :

The values stored in the various containers can be of any assignable data type. To qualify, a type must provide a default constructor, a copy constructor, and an assignment operator. This covers most data types you are likely to want to store in a container, including basic types such as int and double, pointer types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM