singleton パターンです。
気が向けばそのうち解説文を書きます。
#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;
}
最終更新:2010年08月26日 05:23