April 2018
Beginner
714 pages
18h 21m
English
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, ...
Read now
Unlock full access