public member function
<<ios> <iostream>

std::ios_base::register_callback

void register_callback (event_callback fn, int index);
註冊事件回撥函式
fn 註冊為回撥函式,當發生流事件時,將使用 index 作為引數自動呼叫它。

如果有多個回撥函式被註冊,它們都會被呼叫,呼叫的順序與註冊時的順序相反。

回撥函式必須是可轉換為 event_callback 的型別。並且它由一個等價於以下表達式的語句呼叫:

1
(*fn)(ev,stream,index)

其中 index 是使用此函式註冊回撥函式時傳遞的 index 引數,stream 是發生事件的流物件的指標,而 ev 是成員列舉型別 event 的物件,指示發生了哪個事件。它可以是以下成員值之一:

成員常量事件觸發
copyfmt_event在呼叫成員函式 copyfmt 時(在所有格式標誌已被複制,但在異常掩碼被複制之前)。
erase_event在呼叫流解構函式時(在 basic_ios::copyfmt 的開頭也呼叫)。
imbue_event在呼叫 imbue 時(在函式返回之前)。

在上述所有情況下,所有已註冊的函式都會被呼叫。函式本身可以使用 ev 引數來區分觸發函式呼叫的事件。

引數

fn
要呼叫的函式的指標。
event_callback 成員型別定義如下:

1
typedef void (*event_callback) (event ev, ios_base& ios, int index);
index
作為引數傳遞給回撥函式的整數值。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// stream callbacks
#include <iostream>     // std::cout, std::ios_base
#include <fstream>      // ofstream

void testfn (std::ios::event ev, std::ios_base& stream, int index)
{
  switch (ev)
  {
    case stream.copyfmt_event:
      std::cout << "copyfmt_event\n"; break;
    case stream.imbue_event:
      std::cout << "imbue_event\n"; break;
    case stream.erase_event:
      std::cout << "erase_event\n"; break;
  }
}

int main () {
  std::ofstream filestr;
  filestr.register_callback (testfn,0);
  filestr.imbue (std::cout.getloc());
  return 0;
}

輸出
imbue_event
erase_event


資料競爭

修改流物件。
併發訪問同一個流物件可能導致資料爭用。

異常安全

基本保證:如果丟擲異常,流處於有效狀態。

另見