简体   繁体   English

如何使用 std::istreambuf_iterator 初始化字符串

[英]How to use std::istreambuf_iterator to intialize a string

So I'm trying to read a piece of code which goes所以我正在尝试阅读一段代码

auto runFile(const std::string &path)
{
    const std::string source = ([&]() {
        std::ifstream file(path);
        return std::string{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
    })();
}

Could someone explain to me exactly what's happening in this line:有人可以向我准确解释这一行发生了什么:

return std::string{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};

I understand that it's supposed to return a string that is made up of a range between the two iterators, but i don't exactly understand what range is being selected here.我知道它应该返回一个由两个迭代器之间的范围组成的字符串,但我不完全理解这里选择的范围。

If someone could explain to me how istreambuf works in the first place that would be great too!如果有人可以首先向我解释 istreambuf 的工作原理,那也太好了!

The simpler an answer the better, as I'm new to c++答案越简单越好,因为我是 c++ 的新手

The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator.默认构造的std::istreambuf_iterator称为流结束迭代器。

In other words, the first iterator being passed points to a valid stream and the second iterator being passed, which is default constructed, represents the end of the stream .换句话说,第一个被传递的iterator指向一个有效的stream和第二个被传递的iterator ,它是默认构造的,代表stream的结束。

cppreference参考

When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator.当一个有效的 std::istreambuf_iterator 到达底层 stream 的末尾时,它变得等于 end-of-stream 迭代器。 Dereferencing or incrementing it further invokes undefined behavior.取消引用或增加它会进一步调用未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM