Iterating through an rvalue container
问题 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? 回答1: 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-expression std::vector<int