fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <class T>
  5. class shared_ptrx
  6. {
  7. private:
  8. long *refcount;
  9. T *link;
  10. void decrement() {
  11. if ((--(*refcount)) == 0) {
  12. delete refcount;
  13. if (link != NULL) {
  14. delete link;
  15. }
  16. }
  17. refcount = NULL;
  18. link = NULL;
  19. }
  20. void init(T *t, long c) {
  21. refcount = new long(c);
  22. link = t;
  23. }
  24. void copy(shared_ptrx& p) {
  25. refcount = p.refcount;
  26. link = p.link;
  27. (*refcount)++;
  28. }
  29. public:
  30. shared_ptrx() { init(NULL, 0); }
  31. explicit shared_ptrx(T *t) { init(t, 1); }
  32. explicit shared_ptrx(shared_ptrx& p) { copy(p); }
  33. ~shared_ptrx() { decrement(); }
  34. T& operator * () const { return *link; }
  35. T* operator -> () const { return link; }
  36. explicit operator bool () const {
  37. if (refcount == NULL) return false;
  38. return (*refcount > 0);
  39. }
  40. shared_ptrx& operator = (shared_ptrx& p) {
  41. decrement();
  42. copy(p);
  43. return *this;
  44. }
  45. void reset(T *t) {
  46. decrement();
  47. init(t, 1);
  48. }
  49. void swap(shared_ptrx& p) {
  50. int *rc = p.refcount;
  51. T *temp = p.link;
  52. p.refcount = refcount;
  53. p.link = link;
  54. refcount = rc;
  55. link = temp;
  56. }
  57. };
  58.  
  59. template <class T>
  60. class BaseList
  61. {
  62. private:
  63. BaseList *link;
  64. shared_ptrx<T> data;
  65. public:
  66. BaseList() : link(NULL) { }
  67. BaseList(T *t) : link(NULL) { data.reset(t); }
  68. void attach(const BaseList& p) {
  69. link = &p;
  70. }
  71. };
  72.  
  73. class Value
  74. {
  75. int c;
  76. public:
  77. Value(int v) { c = v; }
  78. ~Value() { cout << "del!" << c << endl; }
  79. void p() { cout << c << endl; }
  80. operator int () { return c; }
  81. };
  82.  
  83. int main() {
  84.  
  85. shared_ptrx<Value> f(new Value(5));
  86. {
  87. shared_ptrx<Value> p(f);
  88. cout << *p << endl;
  89. }
  90. f->p();
  91.  
  92. {
  93. shared_ptrx<Value> m(new Value(8));
  94. shared_ptrx<Value> k(m);
  95. k = f;
  96. k->p();
  97. m->p();
  98. }
  99.  
  100. cout << "finish" << endl;
  101. return 0;
  102. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
5
5
5
8
del!8
finish
del!5