std::basic_ios<CharT,Traits>::copyfmt
来自 cppreference.cn
basic_ios& copyfmt( const basic_ios& other ); |
||
如果 other 指的是与 *this 相同的对象,则没有效果。 否则,将流 other 的状态复制到 *this 中。 这是按以下顺序完成的
2) 将所有成员对象从 other 复制到 *this,但 rdstate()、异常掩码和 rdbuf() 除外。 特别是,复制区域设置、格式化标志、数组 std::ios_base::iword 和 std::ios_base::pword 的内容(但不是
iword
和 pword
指针本身)、回调和关联的流。4) 从 other 复制异常掩码到 *this,如同调用 exceptions(other.exceptions()) 一样。
目录 |
[edit] 参数
other | - | 要用作来源的另一个流 |
[edit] 返回值
*this
[edit] 注释
第二次遍历回调可用于深层复制 std::ios_base::pword 中的指针指向的用户定义对象。
copyfmt()
可用于保存和恢复流的状态。 Boost 提供了更细粒度的 I/O 状态保存器 库,用于相同的目的。
[edit] 示例
使 std::ofstream 对象 "out" 的行为与 std::cout 完全一样,包括格式化,tie()
到 std::cin 等。
运行此代码
#include <bitset> #include <climits> #include <fstream> #include <iostream> int main() { std::ofstream out; out.copyfmt(std::cout); // copy everything except rdstate and rdbuf out.clear(std::cout.rdstate()); // copy rdstate out.basic_ios<char>::rdbuf(std::cout.rdbuf()); // share the buffer 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); // copy everything except rdstate and 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
[edit] 缺陷报告
以下行为改变的缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 256 | C++98 | 步骤 3 使用 未定义的事件类型 copy_event 调用了注册的回调 |
更正为 copyfmt_event |
LWG 292 | C++98 | 如果 other 指的是与 *this 相同的对象,则成员对象 仍然被复制,并且注册的回调仍然被调用 |
在这种情况下不执行任何操作 在这种情况下 |