Hi,
I'm bringing this subject here from the boost.users newsgroup. The
original post was dealing with the following code.
#include <boost/range/adaptor/reversed.hpp>
#include <boost/foreach.hpp>
#include <vector>
#include <iostream>
std::vector<int> getv() {
return std::vector<int>{1,2,3};
}
int main(int argc, char* argv[]) {
// works fine:
BOOST_REVERSE_FOREACH(int i, getv())
std::cout << i << std::endl;
// crashes:
for(int i : boost::adaptors::reverse(getv()))
std::cout << i << std::endl;
return 0;
}
It turns out that the reason for the latter loop to crash is that the
temporary vector returned by getv() gets destroyed too soon, leaving
invalid iterators in the range resulting from 'reverse'. Clearly this
is because of how the range-based for loop is defined/designed.
I find the behavior counter-intuitive. IMHO the language syntax hides
the fact that there is a "hidden semicolon" in the for loop
implementation that causes the temporary to be destroyed soon. I wonder
whether this was an intention for the 'for' loop to behave like this,
and whether there are any advantages of that the temporaries like this
get destroyed so soon.
There is a related proposal by Eric Niebler [
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4128.html ], I
think that in particular sections 3.3.2 and 14.1 are relevant to my
question. However, I'm not interested in just ranges but rather
temporaries in general.
Thanks,
Filip