static 宣言しておいた std::ofstream はちゃんと static
static 変数は int でしか使ったことなくて,C++ の std::ofstream はどうなんだろうな?と VC++ 2008 でテストした.
グローバル関数の func() は期待通りに動作した.ユーザ定義クラス myclass のオブジェクト c が グローバル関数の func() と独立している点も期待通りだ.
期待通りでないのは, d.txt が出力されない点だ.myclass::func() 内で宣言した static 変数がクラス全域に作用している.c.txt も「^^;」が5行でなく10行となっている状態だ.d.func() は c.txt に書き込んでいる.
クラス関数内で宣言した static 変数はクラス変数に昇格するものなのかあ.不思議だなあ.
コード
#include <iostream> #include <fstream> using namespace std; void func(void) { static ofstream ofs("ofstream.txt"); ofs << "^^;" << endl; } class myclass{ char *filename; public: myclass(char *filename) { this->filename = new char[strlen(filename) + 1]; strncpy(this->filename, filename, strlen(filename) + 1); } ~myclass() { delete [] filename; } void func(void) { static ofstream ofs(filename); ofs << "^^;" << endl; } }; int main(void) { func(); func(); func(); func(); func(); myclass c("c.txt"); c.func(); c.func(); c.func(); c.func(); c.func(); myclass d("d.txt"); d.func(); d.func(); d.func(); d.func(); d.func(); return 0; }
結果
ofstream.txt
^^; ^^; ^^; ^^; ^^;
c.txt
^^; ^^; ^^; ^^; ^^; ^^; ^^; ^^; ^^; ^^;
d.txt
存在しない.