std::basic_ios<CharT,Traits>::copyfmt

来自cppreference.com
< cpp‎ | io‎ | basic ios
 
 
 
 
basic_ios& copyfmt(const basic_ios& other );

如果 other*this 指代同一对象,那么没有效果。否则复制流 other 的状态到 *this 中。以下列序列进行:

1) 传递 erase_event 为参数,调用 register_callback() 注册的每个回调。
2)other 复制除了 rdstate()、异常掩码和 rdbuf() 外的所有成员对象到 *this。特别是要复制本地环境,格式化标志,数组 std::ios_base::iwordstd::ios_base::pword 的内容(而不是 iwordpword 指针本身),回调,以及所捆绑的流。
3) 传递 copyfmt_event 为参数,调用 register_callback() 注册的每个回调。
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){returnstd::bitset<sizeof(std::ios_base::fmtflags)*CHAR_BIT>{static_cast<unsignedlonglong>(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 指代同一对象,依然会复制成员对象和调用已注册的回调 此时什么也不做
close