1

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;?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Isn't empty brackets used to avoid most vexing parse?
@Learpcs Yes, there are cases where you can substitute parentheses with curly braces to avoid vexing parses.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.