考虑
std::vector<abc> fun() { return a;}
..
..
for( auto itr = fun().begin(); itr< fun().end(); ++itr) //A
{
..
}
for( auto & itr : fun()) //B
{
}
这里的两个循环都不安全吗? (迭代器不兼容?)
答案 0 :(得分:1)
这是未定义的行为。
for( auto itr = fun().begin(); itr< fun().end(); ++itr) //A
{
..
}
std::vector
中的fun().begin()
与std::vector
返回的fun().end()
完全不同{。}}。
因此,比较itr < fun().end()
为comparing iterators from two different containers, which is undefined behavior。
第二个版本(B)可以正常工作as described in this post。
for (auto & itr : fun()) //B
{
}