「DesignPattern/Singleton/cpp_code1」の編集履歴(バックアップ)一覧はこちら

DesignPattern/Singleton/cpp_code1」(2010/08/26 (木) 21:44:02) の最新版変更点

追加された行は緑色になります。

削除された行は赤色になります。

//cpp/linenumber #include <iostream> class singleton { private : static singleton* p_instance_; static bool destroyed_; public : static singleton& instance() { if (!p_instance_) { if (destroyed_) { on_dead_reference(); } else { create(); } } return *p_instance_; } private : singleton() { std::cout << "コンストラクタ" << std::endl; } singleton(const singleton&) { std::cout << "コピーコンストラクタ" << std::endl; } singleton& operator=(const singleton&) { std::cout << "代入演算子" << std::endl; } virtual ~singleton() { p_instance_ = 0; destroyed_ = true; std::cout << "デストラクタ" << std::endl; } static void create() { static singleton the_instance; p_instance_ = &the_instance; } static void on_dead_reference() { throw std::runtime_error("Dead reference detected."); } }; singleton* singleton::p_instance_ = 0; bool singleton::destroyed_ = false; void foo() { singleton::instance(); } int main() try { foo(); singleton::instance(); } catch(std::exception &e) { std::cerr << e.what() << std::endl; }
//cpp/linenumber #include <iostream> class singleton { private : static singleton* p_instance_; // 唯一のインスタンス static bool destroyed_; // インスタンスの廃棄フラグ public : static singleton& instance() { if (!p_instance_) { if (destroyed_) { // 既にインスタンスが廃棄されていたらエラー on_dead_reference(); } else { // 初回は唯一のインスタンスを生成 create(); } } return *p_instance_; } private : singleton() { std::cout << "コンストラクタ" << std::endl; } singleton(const singleton&) { std::cout << "コピーコンストラクタ" << std::endl; } singleton& operator=(const singleton&) { std::cout << "代入演算子" << std::endl; } virtual ~singleton() { p_instance_ = 0; // ポインタをゼロクリア destroyed_ = true; // 廃棄フラグを立てる std::cout << "デストラクタ" << std::endl; } // 唯一のインスタンス作成 static void create() { static singleton the_instance; p_instance_ = &the_instance; } // 廃棄されたインスタンスを参照しようとしたときに呼び出される static void on_dead_reference() { throw std::runtime_error("Dead reference detected."); } }; // staticメンバ変数の初期化 singleton* singleton::p_instance_ = 0; bool singleton::destroyed_ = false; int main() try { singleton::instance(); } catch(std::exception &e) { std::cerr << e.what() << std::endl; }

表示オプション

横に並べて表示:
変化行の前後のみ表示: