Static再び
またどうでもいいことを思いつく。
昨日書いたStaticクラスのデストラクタに事後処理を書けば,mainの最後でどうこうなんてことしなくてもすむわけで。するとだ,GoFの遅延singleton(?)はここでdeleteしてやればOKではないのか?
#includeusing namespace std; class Hoge { public: static Hoge& get_instance() { if (!inst_) inst_ = new Hoge(); return *inst_; } private: Hoge() { cout << "create" << endl; } ~Hoge() { cout << "delete" << endl;} static void delete_instance() { if (inst_) delete inst_; } class Static { ~Static() { Hoge::delete_instance(); } static Static inst_; }; static Hoge* inst_; }; Hoge* Hoge::inst_ = 0; Hoge::Static Hoge::Static::inst_; int main() { Hoge& hoge = Hoge::get_instance(); }
$ g++ staticsingle.cc $ ./a create delete $
うん。完璧。