所以我有一个结构:
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/