Range-based for and Qt foreach macro

Qt provides the foreach macro for iterating over Qt containers:

QVector<int> x { 1, 2, 3 };
foreach(const int i, x) {
    qDebug() << i;
}

This macro was available long before the range-based for loop made it into the C++ standard, so it's still very common in Qt code, and you should be familiar with it. The foreach loop always creates a temporary constant copy of the iterated object. Since it uses implicit sharing, this is very cheap. If you edit x while iterating over it, the changes will not affect the values of i because the iteration uses a copy, but this also means that such an operation is safe. Note that when using range-based for loop, STL-style iterators, or Java-style iterators, editing the same ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.