This question already has answers here:
Why does using a temporary object in the range-based for initializer result in a crash?
(2个答案)
2年前关闭。
在his report on the Fall 2017 standards meeting中,Herb Sutter给出了以下示例,说明了带有初始化器的基于范围的for语句正在简化什么:
(这个问题might be considered a duplicate但是the answer只是通过写问题而不是通过常规搜索显示的,因此我认为值得在StackOverflow中添加它。)
(2个答案)
2年前关闭。
在his report on the Fall 2017 standards meeting中,Herb Sutter给出了以下示例,说明了带有初始化器的基于范围的for语句正在简化什么:
{
T thing = f();
for (auto& x : thing.items()) {
// Note: “for (auto& x : f().items())” is WRONG
mutate(&x);
log(x);
}
}
为什么for (auto& x : f().items())
错误?也就是说,f().items()
何时会产生未定义的行为,而T thing = f(); ... thing.items()
不会产生未定义的行为?(这个问题might be considered a duplicate但是the answer只是通过写问题而不是通过常规搜索显示的,因此我认为值得在StackOverflow中添加它。)
最佳答案
如果t.items()
返回对t
成员的引用,则f().items()
将为您提供悬空的引用,从而提供不确定的行为。
分解:f()
将是一个临时文件,在items()
调用返回后将被销毁。如果items()
返回对该临时成员的引用,则一旦该临时成员被销毁,它将悬挂。
有关更多详细信息和编写方法的方式,请参见https://stackoverflow.com/a/40955021/309334,这样它们就不会出现此问题。