Consider
std::vector<abc> fun() { return a;}
..
..
for( auto itr = fun().begin(); itr< fun().end(); ++itr) //A
{
..
}
for( auto & itr : fun()) //B
{
}
Are both loops here are unsafe? (iterators not being compatible?)
Consider
std::vector<abc> fun() { return a;}
..
..
for( auto itr = fun().begin(); itr< fun().end(); ++itr) //A
{
..
}
for( auto & itr : fun()) //B
{
}
Are both loops here are unsafe? (iterators not being compatible?)
This is undefined behavior.
for( auto itr = fun().begin(); itr< fun().end(); ++itr) //A
{
..
}
The std::vector
from fun().begin()
will be a completely different std::vector
than that returned from fun().end()
.
Therefore the comparison itr < fun().end()
is comparing iterators from two different containers, which is undefined behavior.
The second version (B) will work fine as described in this post.
for (auto & itr : fun()) //B
{
}