具有qList引用的构造函数,它是如何工作的

Constructor with qList reference, how does it work?

本文关键字:何工作 工作 引用 qList 构造函数 具有      更新时间:2023-10-16

Im在qt中创建了一个模型,并遇到了以下代码:

class StringListModel : public QAbstractListModel
{
     Q_OBJECT
public:
    StringListModel(const QStringList &strings, QObject *parent = 0)
    : QAbstractListModel(parent), stringList(strings) {}
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role) const;
    QVariant headerData(int section, Qt::Orientation orientation,
                     int role = Qt::DisplayRole) const;
private:
   QStringList stringList;
};

现在我想知道,这行吗?如果将一个qstringlist传递到堆栈的本地函数中,并且它超出了作用域,那么这个对象会丢失它的字符串列表吗?

同时阅读:构造函数中的C++引用以及:接受字符串引用的构造函数。坏主意?

有些人说它将是无效的,但有些人说字符串(在他们的例子中)将被复制到局部变量。这真是令人困惑。

如果我理解您的要求,那么您是否担心QStringList &strings是通过引用传递的?

初始化列表调用stringList(const &QStringList)复制构造函数。此复制构造函数将传递的&QStringList对象的状态复制到一个新对象,并将该对象分配给stringList。这样,即使原始&strings超出范围或以其他方式被销毁,也无关紧要,因为stringList指向不同的对象。

在您的第二个链接中,没有调用复制构造函数。。。成员对象被指定指向传递给它的同一对象。如果传递的对象在程序的稍后被销毁,则成员对象仍将指向该销毁的对象,从而使其无效。