fork download
  1. #include <iostream> // std::cout
  2. #include <vector> // std::vector
  3. #include <thread> // std::thread
  4. #include <mutex> // std::mutex, std::unique_lock, std::defer_lock
  5. #include "stdio.h"
  6. class B;
  7.  
  8. template <typename T>
  9. class shared_ptr {
  10. public:
  11. shared_ptr() : count(0),_ptr(nullptr) {}
  12. shared_ptr(T* p) : count(new int(1)), _ptr(p) {printf("new int %d,count = %d\n",*this,*count);}
  13. shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {printf("copy run count=%d\n",*count);}
  14. T* operator->() { return _ptr; }
  15. T& operator*() { return *_ptr; }
  16. shared_ptr<T>& operator=(shared_ptr<T>& other)
  17. {
  18.  
  19. ++*other.count;
  20. if (this->_ptr && 0 == --*this->count)
  21. {
  22. delete count;
  23. delete _ptr;
  24. }
  25. this->_ptr = other._ptr;
  26. this->count = other.count;
  27. printf("= run %d,count = %d\n",*this,*count);
  28. return *this;
  29. }
  30. ~shared_ptr()
  31. {
  32.  
  33. if (--*count == 0)
  34. {
  35. //delete count;
  36. //delete _ptr;
  37. }
  38. printf("distory run %d,%d\n",*this,*count);
  39. }
  40.  
  41. int getRef() { return *count; }
  42. private:
  43. int* count;
  44. T* _ptr;
  45. };
  46.  
  47.  
  48.  
  49. class A
  50. {
  51. public:
  52. A(){printf("A construct run\n");};
  53. ~A(){printf("A disconstruct run\n");};
  54. shared_ptr<B> m_b;
  55. };
  56. class B
  57. {
  58. public:
  59. B(){printf("B construct run\n");};
  60. ~B(){printf("B disconstruct run\n");};
  61. shared_ptr<A> m_a;
  62. };
  63.  
  64. int main()
  65. {
  66. // A a;
  67. // B b;
  68. shared_ptr<A> a(new A); //new出来的A的引用计数此时为1
  69. shared_ptr<B> b(new B); //new出来的B的引用计数此时为1
  70. a->m_b = b; //B的引用计数增加为2
  71. b->m_a = a; //A的引用计数增加为2
  72. }
Success #stdin #stdout 0s 4504KB
stdin
Standard input is empty
stdout
A construct run
new int -1246472800,count = 1
B construct run
new int -1246472784,count = 1
= run 164244512,count = 2
= run 164248688,count = 2
distory run -1246472784,1
distory run -1246472800,1