yohhoyの日記

技術的メモをしていきたい日記

unitbufマニピュレータ

C++標準ライブラリのI/Oストリームにおける知名度の低いマニピュレータ(manipulator)。*1

出力ストリームに対して出力操作毎のフラッシュ(flush)を指示する。*2

#include <iostream>

int x = 42;
std::cout << std::unitbuf;

std::cout << "x=" << x << "\n";
// operator<<呼び出し毎にflushされる

標準エラーストリームstd::cerrは初期状態でstd::ios_base::unitbufフラグがセットされている。*3

C++03 27.3.1/p3-4, 27.4, 27.4.2.1.2/Table 83, 27.4.5.1/p25-26, 27.6.2.3/p4, 27.6.2.5.1/p1より一部引用。

ostream cerr;

4 The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio> (27.8.2).
5 After the object cerr is initialized, cerr.flags() & unitbuf is nonzero. Its state is otherwise the same as required for basic_ios<char>::init (27.4.4.1).

#include <iosfwd>
namespace std {
  // 27.4.5, manipulators:
  // (snip)
  ios_base& unitbuf  (ios_base& str);
  ios_base& nounitbuf(ios_base& str);
  // (snip)
}

Table 83 - fmtflags effects

Element Effect(s) if set
unitbuf flushes output after each output operation;
ios_base& unitbuf(ios_base& str);

25 Effects: Calls str.setf(ios_base::unitbuf).
26 Returns: str.

˜sentry();

4 If ((os.flags() & ios_base::unitbuf) && !uncaught_exception()) is true, calls os.flush().

1 Each formatted output function begins execution by constructing an object of class sentry. (snip)

関連URL

*1:当社比:https://x.com/yohhoy/status/2011376066376696061

*2:ライブラリ仕様上は basic_ostream::sentry クラスのデストラクタでフラッシュ操作が規定される。出力関数の開始時に同クラスオブジェクトを作成し、終了時にデストラクタが呼び出される。

*3:ワイド文字標準エラーストリーム std::wcerr も同様に、初期状態で unitbuf フラグが設定される。