对标题的措辞不正确表示歉意-我不太确定是什么引起了问题
我正在测试QList数组访问并遇到了这个问题。这是使用引用QList
append()函数和QList[]运算符的简单示例。
目标:我试图找出是否将相同的对象(用new
创建)添加到2 QList<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
还是在某处做错了什么?
注意:
T &QList::operator[](int i)
,而不是const T &QList::operator[](int i) const
new
对象而不是存储作用域对象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] << ")";
您比较了另一个[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);