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!

+2


a source to share


2 answers


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.

+7


a source


A stream is passed using a non-const reference, but a temporary can only be passed by a const-reference.



Streams are essentially always passed by a non-const reference, because almost anything you do with a stream can / will change the state of the stream.

+1


a source







All Articles