「DesignPattern/Singleton/cpp_code1」の編集履歴(バックアップ)一覧に戻る

DesignPattern/Singleton/cpp_code1 - (2010/08/26 (木) 05:22:59) のソース

//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;
}