-->

Lvalue istringstream Required for istream_iterator

2019-09-19 05:17发布

问题:

Given a string foo in Visual Studio I can break the words into a vector by doing:

vector fooVec{ istream_iterator<string>(istringstream(foo)), istream_iterator<string>() };

But this won't compile in gcc 5.1. I get the error:

invalid initialization of non-const reference of type std::istream_iterator<std::basic_string<char> >::istream_type& {aka std::basic_istream<char>&} from an rvalue of type std::basic_istream<char>

Now I know that gcc had a bug that was fixed by our own Jonathan Wakely. Is this an extension of that bug or should it be illegal for me to use an Rvalue istringstream here?

回答1:

This is not a gcc bug but an evil MSVC extension. std::istream_iterator::istream_iteraor() requires an lvalue reference. Since istringstream(foo) is a temporary gcc correctly tells you you cannot bind the temporary to the lvalue reference.

The reason this works on MSVC is that previously mentioned extension that allows temporaries to be bound to lvalue references. This allows the non standard compliant code to work on MSVC.

So to answer

Is this an extension of that bug or should it be illegal for me to use an Rvalue istringstream here?

No this is not a bug and you need a non-temporary stream here to construct the istream_iterator.