取自5.4.1的实现
// Explanation of the control word:
// - it's initialized to 1
// - that means both the inner and outer loops start
// - if there were no breaks, at the end of the inner loop, it's set to 0, which
// causes it to exit (the inner loop is run exactly once)
// - at the end of the outer loop, it's inverted, so it becomes 1 again, allowing
// the outer loop to continue executing
// - if there was a break inside the inner loop, it will exit with control still
// set to 1; in that case, the outer loop will invert it to 0 and will exit to
# define Q_FOREACH(variable, container) \
for (QForeachContainer<QT_FOREACH_DECLTYPE(container)> _container_((container)); \
_container_.control && _container_.i != _container_.e; \
++_container_.i, _container_.control ^= 1) \
for (variable = *_container_.i; _container_.control; _container_.control = 0)
Qt的实现有两个loop,分别称为inner-loop和outer-loop,QForeachContainer没什么太多需要探讨的地方,只要知道里面有一个i迭代器表示当前元素,e迭代器表示结束元素,也不讨论到底里面是否安全,显然,outer-loop比inner-loop看起来更复杂,先分离着看
outer-loop的循环判断结束条件是_container_.control && container.i != container.e;
后者是相当普通的判断当前元素是否结束元素,前者是一个control变量(int),其初始值为1
outer-loop的循环执行语句是++container.i, container.control ^= 1
前者是相当普通的迭代器递增,后者则是使control与1异或,这使得control会在0跟1之间来回切换
再来看一下inner-loop
inner-loop的判断条件是control,执行语句是将control赋值为0,也就是说,在没有break的情况下,inner-loop只会执行一次,随后control就会变为0,然后outer-loop使其与1异或,变回1,继续执行循环,这就是整个Q_FOREACH最基本的逻辑
比较好玩的是,当循环里有break,那么inner-loop将control赋值为0的操作就不存在,结果control在outer-loop就会与1异或,变为0,从而退出outer-loop