命名空间
变体
操作

std::basic_ostream<CharT,Traits>::sentry

来自 cppreference.cn
< cpp‎ | io‎ | basic ostream
 
 
 
 
class sentry;

basic_ostream::sentry 类的对象在 std::basic_ostream 的每个执行输出(格式化和非格式化)的成员函数的开头,于局部作用域中构造。其构造函数准备输出流:检查流是否已处于失败状态,刷新 tie()'d 输出流,并在必要时执行其他实现定义的任务。实现定义的清理,以及在必要时刷新输出流,在析构函数中执行,以便保证在输出期间抛出异常时发生。

目录

[编辑] 成员函数

(构造函数)
构造 sentry 对象。所有准备任务都在此处完成
(公有成员函数) [编辑]
(析构函数)
在格式化输出之后或异常之后(如果必要),最终化流对象
(公有成员函数)
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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 397 C++98 析构函数可能调用 os.flush(),这可能会抛出异常 异常不会传播
LWG 442 C++98 operator bool 未声明为 const (在 概要中是 const) 添加了 const
LWG 835 C++98 如果 os 设置了 unitbuf,则析构函数将调用 os.flush(),这
是一个 UnformattedOutputFunction 并创建另一个 sentry 对象
(其析构函数然后创建另一个 sentry 对象,依此类推)
调用
os.rdbuf()->pubsync()
在这种情况下代替

[编辑] 参见

插入格式化数据
(公有成员函数) [编辑]