fork(3) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<class T>
  5. class shr_ptr
  6. {
  7. T* resource;
  8. int* count;
  9. public:
  10. shr_ptr():resource(NULL),count(NULL)
  11. {
  12.  
  13. }
  14.  
  15. shr_ptr(T* res):resource(res)
  16. {
  17. count = new int(1);
  18. }
  19.  
  20. shr_ptr(const shr_ptr<T>& R)
  21. {
  22. if(R.resource!=NULL)
  23. {
  24. resource = R.resource;
  25. count = R.count;
  26. *count = *R.count+1;
  27. }
  28. }
  29.  
  30. ~shr_ptr()
  31. {
  32. if(resource!=NULL && --*(count)==0)
  33. {
  34. delete resource;
  35. delete count;
  36. resource = NULL;
  37. }
  38. }
  39.  
  40. shr_ptr<T>& operator = (const shr_ptr<T>& R)
  41. {
  42. if(R.resource != this->resource)
  43. {
  44. *count--;
  45. resource = R.resource;
  46. count = R.count;
  47. *count++;
  48. }
  49. return *this;
  50. }
  51.  
  52. T* operator ->() const
  53. {
  54. return resource;
  55. }
  56.  
  57. T& operator * () const
  58. {
  59. return *resource;
  60. }
  61.  
  62. T* get () const
  63. {
  64. return resource;
  65. }
  66. };
  67.  
  68.  
  69.  
  70. class A
  71. {
  72. public:
  73. A()
  74. {
  75. cout << "created\n";
  76. }
  77. ~A()
  78. {
  79. cout << "deleted\n";
  80. }
  81. };
  82.  
  83. int main()
  84. {
  85. shr_ptr<A> sh1 = new A;
  86. shr_ptr<A> sh2 = new A;
  87.  
  88. sh1 = sh2;
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
created
created
deleted