【问题标题】:Why do I need to have a default constructor in QVector<MyClass>?为什么我需要在 QVector<MyClass> 中有一个默认构造函数?
【发布时间】:2019-06-12 05:52:28
【问题描述】:

我无法编译以下内容:

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

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

在这种情况下,为什么 item 必须有一个默认构造函数?

【问题讨论】:

  • 可能让QVector::resize能够默认构造items。
  • @user4581301 但同样的事情也应该适用于std::vector。对吗?
  • @KunalPuri 好点。我需要关闭 C++11 并检查一下。
  • vector 仅在您使用 resize 或类似的强制默认构造时才会抱怨。 QVector 可能在幕后发生了更多事情。我将不得不把这个留给对 QT 更熟悉的人。

标签: c++ qt vector qvector


【解决方案1】:

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

有关更多信息,请参阅AnT 的答案here

QVector 要求类型是默认可构造的,因为内部函数 realloc() 的实现方式。

来源:Understanding the Qt containers

【讨论】:

    猜你喜欢
    • 2012-12-25
    • 1970-01-01
    • 2016-01-27
    • 2019-03-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多