首页 > 解决方案 > 来自数组的 QList 请求项未提供正确的参考

问题描述

抱歉,如果标题措辞不正确 - 我不太确定是什么导致了问题

我正在测试 QList 数组访问并遇到了这个问题。这是使用引用QList append()函数和QList[]运算符的直接示例。

目标: 我试图找出是否将相同的对象(使用创建的new)添加到 2QList<int>并更改其中一个对象(或引用)是否会更改另一个。

鉴于我的示例和以下输出,我发现的似乎表明这不是真的:

// Some structure to simluate an object
struct IntStream {
    int i;
};

// Create our lists
QList<IntStream> newlist = QList<IntStream>();
QList<IntStream> another = QList<IntStream>();

// Add 3 IntStream objects to the 2 lists using the same object, printing out the object and its reference
for (int i = 0; i < 3; i++) {
    IntStream *s = new IntStream;
    s->i = i;
    newlist.append(*s);
    another.append(*s);
    qDebug() << QString("%1[%2] = %3 (").arg("newList", QString::number(i), QString::number(i)) << &another[i] << ")";
    qDebug() << QString("%1[%2] = %3 (").arg("another", QString::number(i), QString::number(i)) << &another[i] << ")";
}

// Alter bject at index 1 with some arbitrary value
for (int i = 0; i < 3; i++) {
    if(newlist.at(i).i == 1) {
        qDebug() << "another[1] = " << &another[i];
        qDebug() << "newList[1] = " << &newlist[i];
        another[i].i = 4;
    }
}

// Here, I should see the 2 values match, they do not
qDebug() << QString("%1 == %2 ???").arg(QString::number(newlist.at(1).i), QString::number(another.at(1).i));

这个的输出是:

"newList[0] = 0 (" 0x27c75f88 )
"another[0] = 0 (" 0x27c75f88 )
"newList[1] = 1 (" 0x27c755d0 )
"another[1] = 1 (" 0x27c755d0 )
"newList[2] = 2 (" 0x27c75630 )
"another[2] = 2 (" 0x27c75630 )
another[1] =  0x27c755d0
newList[1] =  0x27c76ef0
"1 == 4 ???"

我应该期待看到4 == 4还是我在某处做错了什么?

笔记:

标签: c++qtpointersreferenceqlist

解决方案


qDebug() << QString("%1[%2] = %3 (").arg("newList", QString::number(i), QString::number(i)) << &another[i] << ")";
qDebug() << QString("%1[%2] = %3 (").arg("another", QString::number(i), QString::number(i)) << &another[i] << ")";

你比较了 &another[i] 的两倍。你应该在第一行写 &newlist[i] 。

当你调用 newlist.append(*s); 您制作了 IntStream 实例的副本。

为了满足您的需求:“我正在尝试确定是否将相同的对象(使用 new 创建的)添加到 2 QList 并更改其中一个对象(或引用)是否会更改另一个。 ”使用 shared_ptr 共享您的实例多个列表之间。

就像是 :

struct IntStream {
    int i;
};

// Create our lists
QList<std::shared_ptr<IntStream >> newlist = QList<std::shared_ptr<IntStream >>();
QList<std::shared_ptr<IntStream >> another = QList<std::shared_ptr<IntStream >>();

// Add 3 IntStream objects to the 2 lists using the same object, printing out the object and its reference
for (int i = 0; i < 3; i++) {
    std::shared_ptr<IntStream > s = std::make_shared<IntStream >();
    s->i = i;
    newlist.append(s);
    another.append(s);

推荐阅读