std::basic_istream<CharT,Traits>::sentry
class sentry; | ||
在每个执行输入(有格式和无格式)的 std::basic_istream 成员函数起始,在块作用域构造一个类 basic_istream::sentry
的对象。其构造函数准备输入流:检查流是否已在失败状态,冲入 tie()
过的输出流,若非设置了 noskipws 标志则跳过前导空白,并在需要时进行其他由实现定义的任务。如果必要则在析构函数中进行所有清理,从而在输入过程中抛出异常的情况下保证清理发生。
目录 |
[编辑]成员类型
traits_type | Traits |
[编辑]成员函数
(构造函数) | 构造 sentry 对象。在此完成所有准备任务。 (公开成员函数) |
(析构函数) | 若需要,则在有格式输入或异常后终止流对象 (公开成员函数) |
operator= [弃置] | 不可复制赋值 (公开成员函数) |
operator bool | 检查流对象的准备是否成功 (公开成员函数) |
std::basic_istream::sentry::sentry
explicit sentry(std::basic_istream<CharT, Traits>& is, bool noskipws =false); | ||
为有格式输入准备流。
如果 is.good() 是 false,那么调用 is.setstate(std::ios_base::failbit) 并返回。否则,如果 is.tie() 不是空指针,那么调用 is.tie()->flush() 将输出序列与外部流同步。is.tie() 的放置区为空时可以抑制此调用。实现可以延迟对 flush() 的调用,直到发生对 is.rdbuf()->underflow() 的调用。如果在销毁 sentry 对象前未出现这种调用,那么它可以被完全消除。
如果 noskipws 为零且 is.flags()&std::ios_base::skipws 不为零,那么函数提取并舍弃所有空白字符,直到下个可用字符不是空白字符(由当前 is 中浸染的本地环境确定)。如果 is.rdbuf()->sbumpc() 或 is.rdbuf()->sgetc() 返回 traits::eof(),那么此函数调用 setstate(std::ios_base::failbit|std::ios_base::eofbit)(可能会抛出 std::ios_base::failure)。
可能会发生由实现定义的其他准备,其可能会调用 setstate(std::ios_base::failbit)(可能会抛出 std::ios_base::failure)。
如果准备完成后 is.good()==true,那么对 operator bool 的任何后继调用都会返回 true。
参数
is | - | 要准备的文件流 |
noskipws | - | 不应跳过空白时是 true |
异常
在跳过空白符且出现文件尾条件时抛出 std::ios_base::failure。
std::basic_istream::sentry::~sentry
~sentry(); | ||
不做任何事。
std::basic_istream::sentry::operator bool
explicit operator bool()const; | ||
检查输入流准备是否成功。
参数
(无)
返回值
输入流初始化成功时返回 true,否则返回 false。
[编辑]示例
#include <iostream>#include <sstream> struct Foo {char n[5];}; std::istream& operator>>(std::istream& is, Foo& f){ std::istream::sentry s(is);if(s) is.read(f.n, 5);return is;} int main(){std::string input =" abcde";std::istringstream stream(input); Foo f; stream >> f;std::cout.write(f.n, 5);std::cout<<'\n';}
输出:
abcde
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 195 | C++98 | 不明确构造函数是否会设置 eofbit | 使之明确 |
LWG 419 | C++98 | 构造函数在已设置 eofbit 的情况下不会设置 | 此时会设置 failbit |
[编辑]参阅
提取带格式数据 (公开成员函数) | |
提取字符和字符数组 (函数模板) |