C++ 具名要求:有格式输出函数 (FormattedOutputFunction)
要求
有格式输出函数 (FormattedOutputFunction) 是进行下列操作的 std::basic_ostream 成员函数或涉及 std::basic_ostream 的非成员函数:
- 构造一个 std::basic_ostream::sentry 类型对象 sentry。
- 如果 bool(sentry) 是 true,那么如同以调用 rdbuf()->sputc() 试图通过插入字符到输出流来进行想要的输出。也有可能会使用 std::basic_ostream 的其他公开成员,但不会调用 rdbuf() 的除了 overflow(),xsputn() 和 sync() 以外的其他虚成员。
- 销毁 sentry 并返回 *this。
如果 sentry 构造失败,或者 bool(sentry) 是 false,那么就不会进行输出。
如果无法生成输出,那么就会调用 setstate(std::ios_base::failbit),它可能会抛出异常。
如果在输出过程中抛出了异常,那么就会在不抛出 std::ios_base::failure 的情况下在 *this 的错误状态中设置 badbit。如果此流的异常掩码中启用了 badbit 上的异常(即 (exceptions() & badbit) != 0),那么还会重抛该异常。
在从有格式输出函数抛出异常的情况下,从函数离开前也会销毁 sentry。
填充
|
有格式输出函数根据 std::num_put::do_put() 阶段 3 的规则决定如何填充。 |
(C++14 前) |
|
流 os 的有格式输出函数通过以下方式决定如何填充。 给定一个 如果 (os.flags() & std::ios_base::adjustfield) == std::ios_base::left 是 true,那么会在字符序列后面填充;否则会在字符序列前面填充。 |
(C++14 起) |
标准库
下列标准库函数是有格式输出函数 (FormattedOutputFunction) 。
- basic_ostream::operator<<(std::basic_ostream&, int / long / double / void* / bool)
- operator<<(std::basic_ostream&, char)
- operator<<(std::basic_ostream&, char*)
- operator<<(std::basic_ostream&, const std::bitset&)
- operator<<(std::basic_ostream&, const std::basic_string&)
-
operator<<,在 std::put_money 的返回值上调用时。
| (C++17 起) |
|
(C++23 起) |
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 160 | C++98 | 确定是否需要重抛异常的流程中提到了不存在的函数 exception() | 改成 exceptions() |
| LWG 165 | C++98 | 能在 rdbuf() 上调用的虚成员只有 overflow()
|
也可以调用 xsputn() 和 sync()
|