fork download
  1. #include <iostream>
  2. #include <set>
  3.  
  4. using namespace std;
  5.  
  6. class taco
  7. {
  8. static set<taco *> chain; // 自分自身のポインタを入れるstaticなコンテナ
  9.  
  10. private:
  11. // コンストラクタ
  12. taco()
  13. {
  14. // コンストラクタで自分自身のポインタをチェーンに追加
  15. chain.insert(this);
  16. }
  17.  
  18. ~taco()
  19. {}
  20.  
  21. public:
  22. static taco * createinstance()
  23. {
  24. return new taco();
  25. }
  26.  
  27. static size_t count()
  28. {
  29. return chain.size();
  30. }
  31.  
  32. static void release()
  33. {
  34. typedef set<taco *>::iterator iterator;
  35. for( iterator it = chain.begin(); it != chain.end(); )
  36. {
  37. iterator next = it;
  38. ++next;
  39.  
  40. delete *it;
  41. chain.erase(it);
  42.  
  43. it = next;
  44. }
  45. //c++11からはこのように書ける。
  46. //for( iterator it = chain.begin(); it != chain.end(); )
  47. //{
  48. //eraseは削除された位置の次の位置を指すイテレータを返す。
  49. //it = chain.erase(it);
  50. //}
  51. }
  52. };
  53.  
  54. // 静的メンバの実体
  55. set<taco *> taco::chain;
  56.  
  57.  
  58. int main()
  59. {
  60. // ポインタに紐付けしない
  61. taco::createinstance();
  62. taco::createinstance();
  63. taco::createinstance();
  64. taco::createinstance();
  65. taco::createinstance();
  66.  
  67. cout << "there are " << taco::count() << " objects in the memory." << endl;
  68.  
  69. taco::release();
  70.  
  71. cout << "there are " << taco::count() << " objects in the memory." << endl;
  72. }
  73.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
there are 5 objects in the memory.
there are 0 objects in the memory.