std::basic_ios<CharT,Traits>::tie
來自 cppreference.com
std::basic_ostream<CharT, Traits>* tie() const; |
(1) | |
std::basic_ostream<CharT, Traits>* tie( std::basic_ostream<CharT, Traits>* str ); |
(2) | |
管理繫結的流。繫結的流是一個輸出流,它與流緩衝區(rdbuf())控制的序列同步,也就是說,在對 *this 進行任何輸入/輸出操作之前,會在繫結的流上呼叫 flush()。
1) 返回當前繫結的流。如果沒有繫結的流,則返回空指標。
2) 將當前繫結的流設定為 str。返回操作前的繫結的流。如果沒有繫結的流,則返回空指標。如果 str 不為空,並且從 str->tie() 開始遍歷繫結的流物件的連結串列可以訪問到 tie(),則行為未定義。
目錄 |
[編輯] 引數
str | - | 要設定為繫結的流的輸出流 |
[編輯] 返回值
繫結的流,如果沒有繫結的流,則為空指標。
[編輯] 異常
可能丟擲實現定義的異常。
[編輯] 注意
預設情況下,標準流 std::cout 繫結到 std::cin 和 std::cerr。類似地,它的寬字元對應物 std::wcout 繫結到 std::wcin 和 std::wcerr。
[編輯] 示例
執行此程式碼
#include <fstream> #include <iomanip> #include <iostream> #include <string> int main() { std::ofstream os("test.txt"); std::ifstream is("test.txt"); std::string value("0"); os << "Hello"; is >> value; std::cout << "Result before tie(): " << std::quoted(value) << "\n"; is.clear(); is.tie(&os); is >> value; std::cout << "Result after tie(): " << std::quoted(value) << "\n"; }
輸出
Result before tie(): "0" Result after tie(): "Hello"
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 835 | C++98 | 兩個流可能相互繫結[1] (直接或透過另一箇中間流物件) |
在這種情況下行為未定義 |
- ↑ std::basic_ostream::flush() 是一個 UnformattedOutputFunction,因此在呼叫它時會建立一個哨兵物件。當在一個流物件上呼叫
flush()
時,哨兵物件的建構函式將在其繫結的流上呼叫flush()
,而該flush()
將構造另一個哨兵物件,其建構函式將在此流的繫結的流上呼叫flush()
,依此類推。因此,如果流 a 和 b (直接或間接) 相互繫結,則呼叫 a.flush() 最終將呼叫 b.flush(),後者最終將呼叫 a.flush(),從而導致無限迴圈。