Why can't I build a std :: istream_iterator with an unnamed temp?
g ++ allows this istream_iterator construct from an ifstream instance:
std::ifstream ifstr("test.txt");
std::istream_iterator<std::string> iter1(ifstr);
... but it doesn't allow for the same construct with an unnamed temporary:
std::istream_iterator<std::string> iter2(std::ifstream("test.txt"));
This gives:
error: there is no corresponding function to call 'std :: istream_iterator, ptrdiff_t> :: istream_iterator (std :: ifstream)
Does anyone know why this is not working? - thanks!
a source to share
It is not, because the constructor parameter istream_iterator
is a non-const reference, but you provide a temporary one. You cannot provide temporary (i.e. rvalues) non-const references.
But, otherwise, even if it references a constant, it still won't work because it ifstream
can't be copied. Curiously, C ++ requires an accessible copy constructor to bind rvalues to a non-const reference.
a source to share