std::basic_ostream<CharT,Traits>::sentry
来自 cppreference.cn
< cpp | io | basic_ostream
class sentry; |
||
在 std::basic_ostream 的每个执行输出(格式化和非格式化)的成员函数的开头,在局部作用域内构造一个 basic_ostream::sentry
类的对象。其构造函数准备输出流:检查流是否已处于失败状态,刷新 tie() 关联的输出流,并在必要时执行其他实现定义的任务。实现定义的清理以及在必要时刷新输出流都在析构函数中执行,从而保证在输出期间抛出异常时也会发生清理。
目录 |
[编辑] 成员函数
(构造函数) |
构造哨兵对象。所有准备任务都在这里完成。 (公共成员函数) |
(析构函数) |
在格式化输出或异常后,如有必要,完成流对象。 (公开成员函数) |
operator= |
赋值运算符已删除 (公开成员函数) |
operator bool |
检查流对象的准备是否成功 (公共成员函数) |
std::basic_ostream::sentry::sentry
explicit sentry( std::basic_ostream<CharT, Traits>& os ); |
||
为格式化输出准备流。
如果 os.good() 为 false,则返回。否则,如果 os.tie() 不是空指针,则调用 os.tie()->flush() 以将输出序列与外部流同步。在准备期间,构造函数可能会调用 setstate(failbit)(这可能会抛出 std::ios_base::failure)。
如果准备完成后,os.good() == true,则后续对 operator bool 的调用将返回 true。
参数
os | - | 要准备的输出流 |
异常
如果发生文件结束条件,则为 std::ios_base::failure。
std::basic_ostream::sentry::~sentry
~sentry(); |
||
如果 (os.flags() & std::ios_base::unitbuf) && !std::uncaught_exception() && os.good()) 为 true,则调用 os.rdbuf()->pubsync()。如果该函数返回 -1,则在 os.rdstate() 中设置 badbit,而不传播异常。
std::basic_ostream::sentry::operator bool
explicit operator bool() const; |
||
检查输出流的准备是否成功。
参数
(无)
返回值
如果输出流的准备成功,则为 true,否则为 false。
[编辑] 示例
运行此代码
#include <iostream> #include <sstream> struct Foo { char n[6]; }; std::ostream& operator<<(std::ostream& os, Foo& f) { std::ostream::sentry s(os); if (s) os.write(f.n, 5); return os; } int main() { Foo f = {"abcde"}; std::cout << f << '\n'; }
输出
abcde
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 397 | C++98 | 析构函数可能调用 os.flush(),这可能会抛出异常 | 异常未传播 |
LWG 442 | C++98 | operator bool 未声明为 const (在 概要 中是 const) | 添加了 const |
LWG 835 | C++98 | 如果 os 设置了 unitbuf ,析构函数将调用 os.flush(),而它是一个 UnformattedOutputFunction 并创建另一个哨兵对象 (其析构函数然后创建另一个哨兵对象,依此类推) |
在此情况下调用 os.rdbuf()->pubsync() 代替 |
[编辑] 参阅
插入格式化数据 (公共成员函数) |