为什么我需要在 QVector<MyClass> 中有一个默认构造函数?

Why do I need to have a default constructor in QVector<MyClass>?

我在编译以下内容时遇到问题:

#include <QVector>
#include <QDebug>
#include <vector>

class item
{
    int var;
public:
    //Without default constructor this program will not compile
    //item(){}

    item(int value)
    {
        var = value;
    }
    int getVar()
    {
        return var;
    }
};

int main()
{
    //This code will not compile
    QVector<item> y;
    y.append(item(1));
    qDebug() << y[0].getVar();

    //std::vector however will work despite an absence of a default contructor
    std::vector<item> z;
    z.push_back(item(1));
    qDebug() << z.at(0).getVar();

    return 0;
}

准确地说,追加行不会编译。

为什么在这种情况下项目必须有默认构造函数?

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

有关详细信息,请参阅 AnT's answer here

由于内部函数 realloc() 的实现方式,

QVector 要求类型是默认可构造的。

来源:Understanding the Qt containers