c++ - 来自数组的 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
还是我在某处做错了什么?
笔记:
- 我正在使用
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] << ")";
你比较了 &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);
推荐阅读
- javascript - 我如何查看用户是否已经投票、使用反应以及是否已经投票;停止计票?不和谐.js
- node.js - 无法为我修复无效令牌 - 错误在哪里?
- networking - 如何从不同的网络中删除给定的静态 IP?
- node.js - SendGrid - 如何从使用动态模板发送的一些电子邮件中删除取消订阅链接
- jquery - 当文档加载不触发子元素CSS转换时的jQuery addClass
- azure - 从 http1(会话 id)到 http2 的逻辑应用参数
- java - 如何从 Saxon 的扩展函数返回文档节点?
- kiwi-tcms - 在 Kiwi TCMS 中创建新的测试计划时不显示产品和版本
- node.js - 使用 docker-compose 一次运行多个 Docker 容器
- angular - 如何获取firebase数据库中的列表项