Istream_iterator initialization initialization waiting for input

I have this piece of code. The istream_iterator object is defined and not used, so I expect it to do nothing and the application will finish immediately. But when I started the application, it did not end before I provided some input. Why?

I compile it on ArchLinux with: gcc 4.7.1, with the command: g ++ -std = C ++ 11 filename.cpp

#include <iterator> #include <iostream> using namespace std; int main(int argc, char *argv[]) { istream_iterator<char> input(cin); return 0; } 
+4
source share
3 answers

In standard

24.6.1.1 istream_iterator constructors and destructor [istream.iterator.cons]

 istream_iterator(istream_type& s); 

3 - Effects: Initializes the stream with &s . the value can be initialized during construction or when it is first accessed.

Thus, it is not indicated whether this program will wait for input.

However, it is difficult to understand how istream_iterator can be implemented otherwise; 24.6.1: 1 after it is constructed [...], the iterator reads and stores the value of T , so if reading does not occur during construction, it should appear on operator *() const and on free operator==(const istream_iterator<T> &, const istream_iterator<T> &) , so all the internal state of the iterator must be mutable .

+4
source

Presumably, the istream iterator immediately calls cin >> x to extract the first token and determine if it should become equal to the end iterator. The extraction operation blocks until the stream is closed, the token is retrieved, or a parsing failure is detected.

Please note that the name of the question is incorrect: you not only declared input , but also defined it. If your code accurately reflected the question, it would say

 extern istream_iterator<char> input; // declaration only! 

and there will be no blockage.

+3
source

From the stream you can only “get” each value once, after which it disappears. However, the general need for iterators is to access the value several times without increasing the iterator. Thus, istream_iterator will extract the first value to build and copy it to the internal value, which is then returned when the iterator is dereferenced. It also allows the iterator to determine if it is at the end of input and become the final iterator. With increments, the following value is read.

+2
source

Source: https://habr.com/ru/post/1436372/


All Articles