basic_ostream<CharT, Traits>* tie() const; // (1)
basic_ostream<CharT, Traits>* tie(basic_ostream<CharT, Traits>* tiestr); // (2)
概要
同期する出力ストリームオブジェクトを取得・設定する。
要件
- 引数
tiestrがヌルポインタでは無い場合、tiestrからtie()をたどって再びtiestrに到達できないこと。(C++11 から)
効果
- (1) -
- (2)
*thisに紐づくストリーム(basic_ostream)オブジェクトを引数tiestrに設定する(tie() == tiestrとなる)。
戻り値
- (1)
*thisに紐づいている出力ストリーム(basic_ostream)オブジェクトへのポインタ - (2) 引数
tiestrが設定される前のtie()
備考
- 入力ストリーム(
basic_istream)、および、出力ストリーム(basic_ostream)のtie()に出力ストリームを設定すると、書式化・非書式化入出力を実行するたびにtie()->flush()が実行される。
これにより、*thisで書式化・非書式化入出力を実行する際には必ずtie()で指定された出力ストリームがフラッシュされることが保証される。
なお、この動作は、basic_istream::sentry::sentry、および、basic_ostream::sentry::sentryによって引き起こされる。 - 上記の要件欄の記載は C++11 で追加されたが、これは、
basic_ostream::flush()が非書式化出力であることによる。
(basic_ostream::flush()がtie()で指定された出力ストリームのフラッシュを引き起こし、それが次のフラッシュを引き起こし…となり、無限ループを引き起こしてしまうため)
したがって、明記はされていないものの C++03 まででも必要な要件であるものと思われる。(C++03 では、basic_ostream::flush()が非書式化出力ではない旨の記載が追加されたが、これは誤りということで C++11 で修正された)
なお、この要件は「tieに設定した後でこのようになってはいけない」という意味であるものと思われる。(さもないと、設定したことによって無限ループが生じることを防げない) - 標準入出力ストリームは、以下のような設定が行われている。
例
#include <iostream>
#include <fstream>
#include <string>
void input(std::istream& ifs)
{
std::string s;
if (ifs >> s) {
std::cout << s << '\n';
} else {
std::cout << (ifs.rdstate() & std::ios_base::badbit ? "bad" : "not bad") << ", ";
std::cout << (ifs.rdstate() & std::ios_base::eofbit ? "eof" : "not eof") << ", ";
std::cout << (ifs.rdstate() & std::ios_base::failbit ? "fail" : "not fail") << '\n';
ifs.clear();
}
}
int main()
{
static const char filename[] = "test.txt";
std::ofstream ofs(filename);
std::ifstream ifs(filename);
ofs << "new content\n";
input(ifs); // 出力してもフラッシュされていなければ入力できない
ifs.tie(&ofs);
input(ifs); // tie していれば入力時に自動的にフラッシュされる
}
出力
not bad, eof, fail
new
バージョン
言語
- C++98
参照
cincoutcerrwcinwcoutwcerrbasic_istream::sentry::sentrybasic_ostream::sentry::sentry- 60. What is a formatted input function?
C++03 でbasic_ostream::flush()が非書式化出力ではないと明記された Defect Report - 581. flush() not unformatted function
上記の Defect Report で非書式化出力ではなくなってしまったbasic_ostream::flush()を非書式化出力に変更する Defect Report - 835. Tying two streams together (correction to DR 581)
tiestrに関する要件を追加する Defect Report