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;
?
Asked
Active
Viewed 123 times
1

Warpstar22
- 567
- 4
- 19
1 Answers
2
{}
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.

eerorika
- 232,697
- 12
- 197
- 326
-
Isn't empty brackets used to avoid [most vexing parse](https://stackoverflow.com/questions/14077608/what-is-the-purpose-of-the-most-vexing-parse)? – Learpcs Feb 24 '22 at 15:42
-
@Learpcs Yes, there are cases where you can substitute parentheses with curly braces to avoid vexing parses. – eerorika Feb 24 '22 at 18:25