gpt4 book ai didi

qt - 复制后 QStringList 迭代器的结尾似乎无效

转载 作者:行者123 更新时间:2023-12-02 11:09:29 24 4
gpt4 key购买 nike

谁能解释一下,为什么下面的代码根据复制 QStringList 会产生不同的结果:

    #include <stdio.h>
#include <QStringList>

bool qtTest(bool b)
{
QStringList list;
list.push_back("0");
list.push_back("1");
list.push_back("2");

QStringList::const_iterator it = list.end();

if (b) {
// 'static' to prevent optimization
static QStringList copy = list;
}

--it; // 2
--it; // 1
--it; // 0
++it; // 1
++it; // 2
--it; // 1
++it; // 2
++it; // end

return it == list.end();
}

int main(int, char *[])
{
printf("equality with copy: %d", qtTest(true));
printf("equality without copy: %d", qtTest(false));

return 0;
}

输出:
equality with copy: 0
equality without copy: 1

但是,无论复制如何, std::vector 都提供相等的输出。

Debian 7 x86
GCC x86 32 位
Qt 5.1.0 调试
qmake 规范 linux-g++

感谢您的回答

最佳答案

发生这种情况是因为 QStringList 是 Qt 的隐式共享类之一,这意味着当您进行复制时,您实际上只是在复制对列表内容的引用(“真正的”复制仅在/如果其中一个对象被修改时发生)。

如果你想像你在这里做的那样迭代,你应该用 constEnd() 改变 end() 方法,就像这样:

QStringList::const_iterator it = list.constEnd();

if (b) {
// 'static' to prevent optimization
static QStringList copy = list;
}

--it; // 2
--it; // 1
--it; // 0
++it; // 1
++it; // 2
--it; // 1
++it; // 2
++it; // end

return it == list.constEnd();

end() 方法返回一个迭代器,constEnd()(或 cend())返回一个 const_iterator,因此在这种情况下您需要使用它。如果你想深入研究,有一篇有趣的文章:

http://doc.qt.digia.com/qq/qq12-qt4-iterators.html#implicitsharinganditerators

我希望这可以帮助你。

关于qt - 复制后 QStringList 迭代器的结尾似乎无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17849865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com