Lvalue istringstream Required for istream_iterator?

痞子三分冷 提交于 2019-12-12 03:28:33

问题


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.



来源:https://stackoverflow.com/questions/37546443/lvalue-istringstream-required-for-istream-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!