名稱空間
變體
操作

std::basic_ostream<CharT,Traits>::sentry

來自 cppreference.com
< cpp‎ | io‎ | basic_ostream
 
 
 
 
class sentry;

std::basic_ostream 的每個執行輸出(格式化和非格式化)的成員函式的開頭,在區域性作用域內構造一個 basic_ostream::sentry 類的物件。其建構函式準備輸出流:檢查流是否已處於失敗狀態,重新整理 tie() 關聯的輸出流,並在必要時執行其他實現定義的任務。實現定義的清理以及在必要時重新整理輸出流都在解構函式中執行,從而保證在輸出期間丟擲異常時也會發生清理。

目錄

[編輯] 成員函式

(建構函式)
構造哨兵物件。所有準備任務都在這裡完成。
(公共成員函式) [編輯]
(解構函式)
在格式化輸出或異常後,如有必要,完成流物件。
(公開成員函式)
operator=
賦值運算子已刪除
(公開成員函式)
operator bool
檢查流物件的準備是否成功
(公共成員函式) [編輯]

std::basic_ostream::sentry::sentry

explicit sentry( std::basic_ostream<CharT, Traits>& os );

為格式化輸出準備流。

如果 os.good()false,則返回。否則,如果 os.tie() 不是空指標,則呼叫 os.tie()->flush() 以將輸出序列與外部流同步。在準備期間,建構函式可能會呼叫 setstate(failbit)(這可能會丟擲 std::ios_base::failure)。

如果準備完成後,os.good() == true,則後續對 operator bool 的呼叫將返回 true

引數

os - 要準備的輸出流

異常

如果發生檔案結束條件,則為 std::ios_base::failure


std::basic_ostream::sentry::~sentry

~sentry();

如果 (os.flags() & std::ios_base::unitbuf) && !std::uncaught_exception() && os.good())true,則呼叫 os.rdbuf()->pubsync()。如果該函式返回 -1,則在 os.rdstate() 中設定 badbit,而不傳播異常。


std::basic_ostream::sentry::operator bool

explicit operator bool() const;

檢查輸出流的準備是否成功。

引數

(無)

返回值

如果輸出流的準備成功,則為 true,否則為 false

[編輯] 示例

#include <iostream>
#include <sstream>
 
struct Foo
{
    char n[6];
};
 
std::ostream& operator<<(std::ostream& os, Foo& f)
{
    std::ostream::sentry s(os);
    if (s)
        os.write(f.n, 5);
    return os;
}
 
int main()
{
    Foo f = {"abcde"};
    std::cout << f << '\n';
}

輸出

abcde

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 397 C++98 解構函式可能呼叫 os.flush(),這可能會丟擲異常 異常未傳播
LWG 442 C++98 operator bool 未宣告為 const (在 概要 中是 const) 添加了 const
LWG 835 C++98 如果 os 設定了 unitbuf,解構函式將呼叫 os.flush(),而
它是一個 UnformattedOutputFunction 並建立另一個哨兵物件
(其解構函式然後建立另一個哨兵物件,依此類推)
在此情況下呼叫
os.rdbuf()->pubsync()
代替

[編輯] 參閱

插入格式化資料
(公共成員函式) [編輯]