In his report on the Fall 2017 standards meeting, Herb Sutter has the following example of what the range-based for statement with initializer is simplifying:
{
T thing = f();
for (auto& x : thing.items()) {
// Note: “for (auto& x : f().items())” is WRONG
mutate(&x);
log(x);
}
}
Why is for (auto& x : f().items())
wrong? That is, when does f().items()
yield undefined behavior but T thing = f(); ... thing.items()
not yield it?
(This question might be considered a duplicate but the answer was only revealed by writing the question, not by normal search, so I decided it was worthwhile including in StackOverflow.)