What just happened?

We created a temporary QString object and called its replace() method. This method' s return type is QString &, so it doesn't own the string's data. If we immediately assigned this value to an owning variable, it would be correct because the life of the original temporary QString lasts until the end of the full expression (in this case, the assignment):

QString string = QString("abc").replace('a', 'z');
for(QChar c: string) { // correct
    qDebug() << c;
}

However, the temporary object in the original example doesn't live until the end of the for loop, so this will result in a use-after-free bug. The foreach version of this code would contain an implicit assignment to a variable, so it would be correct.

On the other hand, ...

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.