Is the following code causing undefined behavior?
std::map<int, vector<int>> foo()
{
return ...
}
BOOST_FOREACH(const int& i, foo()[42])
{
std::cout << i << std::endl;
}
If undefined, What is the good way to fix it? What if I use c++11 range-for loop instead of BOOST_FOREACH?
This is, unfortunately, most probably undefined behavior.
The problem is that you have two levels here:
std::map<...>is an r-value, its lifetime will be expanded until the end of the full-expressionstd::vector<int>&is an l-value reference (into an object), its lifetime is that of the object.The problem arises because the code (roughly) expands to something like:
The issue here is in the initialization of
__container:If it where just
foo(), this would work, because the lifetime ofstd::map<...>would be extended to match that of__container, however in this case we get:And thus
__containerends up pointing into the nether.