This, unfortunately, is most likely undefined behavior.
The problem is that you have two levels:
std::map<...> is an r-value, its lifetime will be extended to the end of the full expressionstd::vector<int>& is a reference to an l-value (to an object), its lifetime is an object.
The problem arises because the code (approximately) expands to the following value:
for (<init>: <expr>) {
<body>
}
auto&& __container = <expr>;
for (auto __it = begin(container), __e = end(container); __it != __e; ++__it)
{
<init> = *__it;
<body>
}
The problem here is in the initialization __container:
auto&& __container = foo()[42];
foo(), , std::map<...> , __container, :
std::vector<int>& __container = { std::map<...> m = foo(); m[42] };
, , __container , .