O'Reilly logo

Game Programming using Qt 5 Beginner's Guide - Second Edition by Lorenz Haas, Witold Wysota, Pavel Strakhov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required