std::basic_ios<CharT,Traits>::copyfmt
來自 cppreference.com
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())。
目錄 |
[編輯] 引數
其他 | - | 要用作源的另一個流 |
[編輯] 返回值
*this
[編輯] 注意
第二次遍歷回撥可用於深度複製 std::ios_base::pword 中指標指向的使用者定義物件。
copyfmt()
可用於儲存和恢復流的狀態。Boost 為此目的提供了一個更細粒度的 I/O 狀態儲存器 庫。
[編輯] 示例
使 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
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 256 | C++98 | 步驟 3 使用了事件型別 copy_event 呼叫已註冊的回撥,但該型別未定義。event type copy_event , which is not defined |
更正為 copyfmt_event |
LWG 292 | C++98 | 如果 other 指的是與 *this 相同的物件,則仍會複製成員物件並呼叫已註冊的回撥。 were still copied and the registered callbacks were still called |
do nothing 在這種情況下 |