左值istringstream istream_iterator是否需要? [英] Lvalue istringstream Required for istream_iterator?
问题描述
鉴于Visual Studio中的string foo
,我可以通过以下方式将单词分解为vector
:
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>() };
但这不会在gcc 5.1中编译.我收到错误消息:
But this won't compile in gcc 5.1. I get the error:
std::basic_istream<char>
类型的右值对std::istream_iterator<std::basic_string<char> >::istream_type&
类型的非常量引用{akastd::basic_istream<char>&
}的无效初始化
invalid initialization of non-const reference of type
std::istream_iterator<std::basic_string<char> >::istream_type&
{akastd::basic_istream<char>&
} from an rvalue of typestd::basic_istream<char>
现在,我知道gcc拥有已修复的一个错误由我们自己的 Jonathan Wakely .这是该错误的扩展,还是在这里使用Rvalue istringstream
对我来说是非法的?
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?
推荐答案
这不是gcc错误,而是 std::istream_iterator::istream_iteraor()
需要左值引用.由于istringstream(foo)
是临时gcc正确地告诉您您不能将临时绑定到左值引用.
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.
之所以在MSVC上起作用,是因为前面提到的扩展允许临时对象绑定到左值引用.这样,非标准兼容代码就可以在MSVC上运行.
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.
要回答
这是该错误的扩展,还是在这里使用Rvalue
istringstream
对我来说是非法的?
Is this an extension of that bug or should it be illegal for me to use an Rvalue
istringstream
here?
不,这不是bug,您在这里需要一个非临时流来构造istream_iterator
.
No this is not a bug and you need a non-temporary stream here to construct the istream_iterator
.
这篇关于左值istringstream istream_iterator是否需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!