std::basic_ios<CharT,Traits>:: copyfmt
|
basic_ios
&
copyfmt
(
const
basic_ios
&
other
)
;
|
||
如果 other 与 * this 引用同一对象,则不产生任何效果。否则,将流 other 的状态复制到 * this 中。此操作按以下顺序执行:
iword
和
pword
指针本身)、回调函数以及绑定的流。
目录 |
参数
| 其他 | - | 用作源的另一个流 |
返回值
* this
注释
第二次遍历回调函数可用于深度复制由 std::ios_base::pword 中指针所指向的用户自定义对象。
copyfmt()
可用于保存和恢复流的状态。为实现相同目的,Boost 提供了一个更细粒度的
I/O 状态保存器
库。
示例
使
std::ofstream
对象 "out" 的行为完全等同于
std::cout
,包括格式化、与
std::cin
的
tie()
关联等。
#include <bitset> #include <climits> #include <fstream> #include <iostream> int main() { std::ofstream out; out.copyfmt(std::cout); // 复制除 rdstate 和 rdbuf 外的所有内容 out.clear(std::cout.rdstate()); // 复制 rdstate out.basic_ios<char>::rdbuf(std::cout.rdbuf()); // 共享缓冲区 out << "Hello, world\n"; auto bin = [](std::ios_base::fmtflags f) { return std::bitset<sizeof(std::ios_base::fmtflags) * CHAR_BIT> { static_cast<unsigned long long>(f) }; }; std::ofstream out2; std::cout << "1) out2.flags(): " << bin(out2.flags()) << '\n'; std::cout << "2) cout.flags(): " << bin(std::cout.flags()) << '\n'; std::cout.setf(std::ios::hex | std::ios::fixed | std::ios::boolalpha); std::cout << "3) cout.flags(): " << bin(std::cout.flags()) << '\n'; out2.copyfmt(std::cout); // 复制除 rdstate 和 rdbuf 外的所有内容 std::cout << "4) out2.flags(): " << bin(out2.flags()) << '\n'; }
可能的输出:
Hello, world 1) out2.flags(): 00000000000000000001000000000010 2) cout.flags(): 00000000000000000001000000000010 3) cout.flags(): 00000000000000000001000000001111 4) out2.flags(): 00000000000000000001000000001111
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| 缺陷报告 | 适用标准 | 发布行为 | 正确行为 |
|---|---|---|---|
| LWG 256 | C++98 |
步骤3使用未定义的事件类型
copy_event
调用已注册的回调函数 |
修正为
copyfmt_event |
| LWG 292 | C++98 |
若
other
与
*
this
指向同一对象,
仍会复制成员对象并调用已注册的回调函数 |
此情况下
不执行任何操作 |