I found this answer on stack overflow for reading a stream into a string . The code std::string s(std::istreambuf_iterator<char>(stream), {});
works just fine for what I was doing, but I was really confused about the {}
. As far as I can tell this is using the std::string
constructor that uses a begin and end iterator, but I've never seen an iterator defined with {}
. What does that mean and how is it achieving the same thing as std::istreambuf_iterator<char> eos;
?
{}
is a braced initialiser list in this context. It is a list of initialisers used to initialise an object. It is used to initialise a temporary object.
In this case, the list of initialisers is empty. In such case, the object will be value initialised. In case of a non-trivially-default-constructible class such as std::istreambuf_iterator
value initialisation means that the default constructor will be used.
A default consturcted std::istreambuf_iterator
is a sentinel that represents end of stream. This is a feature specific to stream iterators and not to all other iterators.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.