Namespaces
Variants

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

From cppreference.net
basic_ios & copyfmt ( const basic_ios & other ) ;

如果 other * this 引用同一对象,则不产生任何效果。否则,将流 other 的状态复制到 * this 中。此操作按以下顺序执行:

1) 调用所有通过 register_callback() 注册的回调函数,并以 erase_event 作为参数传递。
2) 将除 rdstate() 、异常掩码和 rdbuf() 之外的所有成员对象从 other 复制到 * this 。特别地,会复制区域设置、格式化标志、数组 std::ios_base::iword std::ios_base::pword 的内容(但不包括 iword pword 指针本身)、回调函数以及绑定的流。
3) 调用所有通过 register_callback() 注册的回调函数,并以 copyfmt_event 作为参数传递。
4) 将异常掩码从 other 复制到 * this ,如同通过调用 exceptions ( other. exceptions ( ) ) 实现。

目录

参数

其他 - 用作源的另一个流

返回值

* 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 指向同一对象,
仍会复制成员对象并调用已注册的回调函数
此情况下
不执行任何操作