c++ - 复杂类型的 QVector 与 std::vector

标签 c++ stl qt5

所以我有一个结构:

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

请注意,它没有默认构造函数 Alarm() . 我想要一个包含这种结构对象的 vector 容器。如果我尝试使用 QVector代码无法在我尝试附加新对象的代码中编译并出现此错误:

/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();

看来 QVector要求它持有的类有一个默认的构造函数。但是,使用 std::vector<T>编译得很好。

我的问题是为什么? 这是使用 QVector 的要求吗?有一个带有默认构造函数的类?或者我没有正确使用容器?

最佳答案

std::vector 工作方式不同的原因在于,在 vector 中,分配未初始化的原始内存,然后在需要时调用复制构造函数进行复制。此过程不需要为 resize() 调用默认构造函数。这就是为什么不存在对默认构造函数的依赖性。

另一方面,由于内部函数 realloc() 的实现方式,QVector 要求类型是默认可构造的。

根据 QT 文档:

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

关于c++ - 复杂类型的 QVector 与 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033913/

相关文章:

c++ - 如何将 PHYSICAL_MONITOR 与监视器 DeviceID 关联

c++ - 更喜欢 unordered_set 而不是 vector

c++ - std::map 和二叉搜索树

c++ - #include QtWebKit (Qt4) 或 QtWebKitWidgets (Qt<5.6) 或 QtWebEngineWidgets (Qt>=5.6)

c++ - initializeDb 中的 QPainter#drawText 段错误

java - 我应该同时学习C++和Java吗?

c++ - Catch2 - undefined reference

c++使用方法作为函数的参数

c++ - Boost/STL 在高性能计算方面是否慢?

c++ - 如何在 Windows 上找到 Qt5 CMake 模块