fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class s_ptr
  6. {
  7. public:
  8. s_ptr<T>(T* ptr)
  9. {
  10. ref_count = new size_t(1);
  11. this->ptr = ptr;
  12. }
  13. s_ptr<T>(const s_ptr<T>& rhs)
  14. {
  15. this->ref_count = rhs.ref_count;
  16. this->ptr = rhs.ptr;
  17. (*ref_count)++;
  18. }
  19. ~s_ptr<T>()
  20. {
  21. cout << "Ref count: " << count() << endl;
  22. if (ref_count && (*ref_count) == 1)
  23. {
  24. delete ref_count;
  25. delete ptr;
  26. return;
  27. }
  28. (*ref_count)--;
  29. }
  30.  
  31. s_ptr<T>& operator=(const s_ptr<T>& rhs)
  32. {
  33. if (this != &rhs)
  34. {
  35. ptr = rhs.ptr;
  36. ref_count = rhs.ref_count;
  37. (*ref_count)++;
  38. }
  39. return this;
  40. }
  41.  
  42. size_t count() const
  43. {
  44. return *ref_count;
  45. }
  46. private:
  47. T* ptr = nullptr;
  48. size_t* ref_count = nullptr;
  49. };
  50.  
  51. class Base
  52. {
  53. public:
  54. Base(){cout << "Base()\n";}
  55. ~Base(){cout << "~Base()\n";}
  56. };
  57.  
  58. int main() {
  59. // your code goes here
  60. s_ptr<Base> b(new Base());
  61. s_ptr<Base> bb = b;
  62. s_ptr<Base> bbb(bb);
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
Base()
Ref count: 3
Ref count: 2
Ref count: 1
~Base()