singleton パターンです。

気が向けばそのうち解説文を書きます。


C++
  1. #include <iostream>
  2.  
  3. class singleton {
  4. private :
  5. static singleton* p_instance_; // 唯一のインスタンス
  6. static bool destroyed_; // インスタンスの廃棄フラグ
  7.  
  8. public :
  9. static singleton& instance() {
  10. if (!p_instance_) {
  11. if (destroyed_) { // 既にインスタンスが廃棄されていたらエラー
  12. on_dead_reference();
  13. } else { // 初回は唯一のインスタンスを生成
  14. create();
  15. }
  16. }
  17.  
  18. return *p_instance_;
  19. }
  20.  
  21. private :
  22. singleton() {
  23. std::cout << "コンストラクタ" << std::endl;
  24. }
  25.  
  26. singleton(const singleton&) {
  27. std::cout << "コピーコンストラクタ" << std::endl;
  28. }
  29.  
  30. singleton& operator=(const singleton&) {
  31. std::cout << "代入演算子" << std::endl;
  32. }
  33.  
  34. virtual ~singleton() {
  35. p_instance_ = 0; // ポインタをゼロクリア
  36. destroyed_ = true; // 廃棄フラグを立てる
  37.  
  38. std::cout << "デストラクタ" << std::endl;
  39. }
  40.  
  41. // 唯一のインスタンス作成
  42. static void create() {
  43. static singleton the_instance;
  44. p_instance_ = &the_instance;
  45. }
  46.  
  47. // 廃棄されたインスタンスを参照しようとしたときに呼び出される
  48. static void on_dead_reference() {
  49. throw std::runtime_error("Dead reference detected.");
  50. }
  51. };
  52.  
  53. // staticメンバ変数の初期化
  54. singleton* singleton::p_instance_ = 0;
  55. bool singleton::destroyed_ = false;
  56.  
  57. int main() try {
  58. singleton::instance();
  59. } catch(std::exception &e) {
  60. std::cerr << e.what() << std::endl;
  61. }
  62.  

最終更新:2010年08月26日 05:23