std::istreambuf_iterator
定义于头文件 <iterator> |
||
template< class CharT, class Traits = std::char_traits<CharT> > class istreambuf_iterator |
(直到 C++17) | |
template< class CharT, class Traits = std::char_traits<CharT> > class istreambuf_iterator; |
(自 C++17 起) | |
std::istreambuf_iterator
是一个单程输入迭代器,它从构造时为其提供的 std::basic_streambuf 对象中读取连续的字符。
默认构造的 std::istreambuf_iterator
被称为流结束迭代器。当 std::istreambuf_iterator
到达底层流的末尾时,它变得等于流结束迭代器。进一步解引用或递增它会调用未定义行为。
|
(自 C++11 起) |
内容 |
[编辑] 成员类型
成员类型 | 定义 |
iterator_category
|
std::input_iterator_tag |
value_type
|
CharT |
difference_type
|
typename Traits::off_type |
pointer
|
/* unspecified */ |
reference
|
CharT |
char_type
|
CharT
|
traits_type
|
Traits
|
int_type
|
typename Traits::int_type |
streambuf_type
|
std::basic_streambuf<CharT, Traits> |
istream_type
|
std::basic_istream<CharT, Traits> |
/* proxy */
|
实现定义的类类型。proxy 对象持有一个 char_type 字符和一个 streambuf_type* 指针。使用 operator* 解引用 proxy 对象会产生存储的字符。(仅用于演示的成员类型*) |
成员类型 |
(直到 C++17) |
成员类型 pointer
通常是 CharT*
(参见下文)。
[编辑] 成员函数
构造一个新的 istreambuf_iterator (公有成员函数) | |
(析构函数) (隐式声明) |
析构一个 istreambuf_iterator (公有成员函数) |
获取当前字符的副本 (公有成员函数) | |
推进迭代器 (公有成员函数) | |
测试两个 istreambuf_iterator 是否都为流结束,或者是否都有效(公有成员函数) |
[编辑] 非成员函数
(在 C++20 中移除) |
比较两个 istreambuf_iterator (函数模板) |
[编辑] 注解
LWG issue 659 的解决方案引入了 operator->。 预期给定一个 std::istreambuf_iterator
i,表达式 (*i).m 和 i->m 具有相同的效果。
然而,该解决方案没有提供对其行为的正式规范。因此,它的实现方式有所不同,包括返回 nullptr、返回临时对象的地址,甚至根本不提供该成员。其预期行为几乎无法实现,并且它已通过 LWG issue 2790 的解决方案移除。
LWG issue 659 的解决方案还将成员类型 pointer
设置为未指定,以便允许 operator->
返回代理。 这是为了允许当 CharT
不是类类型时 operator->
能够编译。
[编辑] 示例
#include <iostream> #include <iterator> #include <sstream> #include <string> int main() { // typical use case: an input stream represented as a pair of iterators std::istringstream in{"Hello, world"}; std::istreambuf_iterator<char> it{in}, end; std::string ss{it, end}; std::cout << "ss has " << ss.size() << " bytes; " "it holds \"" << ss << "\"\n"; // demonstration of the single-pass nature std::istringstream s{"abc"}; std::istreambuf_iterator<char> i1{s}, i2{s}; std::cout << "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; ++i1; std::cout << "after incrementing i1, but not i2:\n" "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; ++i2; std::cout << "after incrementing i2, but not i1:\n" "i1 returns '" << *i1 << "'\n" "i2 returns '" << *i2 << "'\n"; }
输出
ss has 12 bytes; it holds "Hello, world" i1 returns 'a' i2 returns 'a' after incrementing i1, but not i2: i1 returns 'b' i2 returns 'b' after incrementing i2, but not i1: i1 returns 'c' i2 returns 'c'
[编辑] 缺陷报告
以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 659 | C++98 | 1. std::istreambuf_iterator 没有 operator->2. 成员类型 pointer 被指定为 CharT* |
1. 已添加 2. 设置为未指定 |
LWG 2790 | C++98 | 由 LWG issue 659 添加的 operator-> 没有用处 | 已移除 |
[编辑] 参见
写入 std::basic_streambuf 的输出迭代器 (类模板) | |
从 std::basic_istream 读取的输入迭代器 (类模板) |