std::basic_ios<CharT,Traits>::copyfmt
来自cppreference.com
<tbody>
</tbody>
basic_ios& copyfmt( const basic_ios& other ); |
||
如果 other 与 *this 指代同一对象,那么没有效果。否则复制流 other 的状态到 *this 中。以下列序列进行:
2) 从
other 复制除了 rdstate()、异常掩码和 rdbuf() 外的所有成员对象到 *this。特别是要复制本地环境,格式化标志,数组 std::ios_base::iword 和 std::ios_base::pword 的内容(而不是 iword 和 pword 指针本身),回调,以及所捆绑的流。4) 从
other 复制异常掩码到 *this,如同通过调用 exceptions(other.exceptions())。参数
| other | - | 用作源的另一个流 |
返回值
*this
注解
通过回调的第二趟可用于深复制 std::ios_base::pword 中的指针所指向的用户定义对象。
copyfmt() 可用于保存和恢复流状态。Boost 为相同目的提供更加细粒度的 IO 状态保存 库。
示例
令 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); // 复制 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 指代同一对象,依然会复制成员对象和调用已注册的回调
|
此时什么也不做 |