为什么我不能用未命名的临时对象构造 std::istream_iterator ?
g++ 允许从 ifstream 实例构造 istream_iterator:
std::ifstream ifstr("test.txt");
std::istream_iterator<std::string> iter1(ifstr);
...但它不允许使用未命名的临时对象进行相同的构造:
std::istream_iterator<std::string> iter2(std::ifstream("test.txt"));
这给出:
错误:没有匹配的函数用于调用 'std::istream_iterator, ptrdiff_t>:: istream_iterator(std::ifstream)'
有谁知道为什么这不起作用? - 谢谢!
g++ allows this construction of an istream_iterator from an ifstream instance:
std::ifstream ifstr("test.txt");
std::istream_iterator<std::string> iter1(ifstr);
...but it doesn't allow the same construction with an unnamed temporary:
std::istream_iterator<std::string> iter2(std::ifstream("test.txt"));
This gives:
error: no matching function for call to ‘std::istream_iterator, ptrdiff_t>::istream_iterator(std::ifstream)’
Does anyone know why this doesn't work? - thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实并非如此,因为 istream_iterator 的构造函数参数是非常量引用,但您提供了一个临时引用。您不能向非常量引用提供临时值(即右值)。
但除此之外,即使它需要一个 const 引用,它仍然不起作用,因为
ifstream
是不可复制的。奇怪的是,C++ 需要一个可访问的复制构造函数来将右值绑定到非常量引用。It doesn't, because
istream_iterator
's constructor parameter is a non-const reference, but you provide a temporary. You cannot provide temporaries (that are rvalues) to non-const references.But aside, even if it would take a const reference, it would still not work, because
ifstream
is not copyable. Curiously, C++ requires an accessible copy constructor to bind an rvalue to a non-const reference.流通过非常量引用传递,但临时数据只能通过常量引用传递。
流本质上总是通过非常量引用传递,因为几乎您对流所做的任何操作都可以/将修改流的状态。
The stream is passed by non-const reference, but a temporary can only be passed by const-reference.
Streams are essentially always passed by non-const reference, because almost anything you do with a stream can/will modify the stream's state.