为什么我不能用未命名的临时对象构造 std::istream_iterator ?

发布于 2024-09-01 02:28:21 字数 434 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥醉 2024-09-08 02:28:22

事实并非如此,因为 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.

简单气质女生网名 2024-09-08 02:28:22

流通过非常量引用传递,但临时数据只能通过常量引用传递。

流本质上总是通过非常量引用传递,因为几乎您对流所做的任何操作都可以/将修改流的状态。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文