Advertisement
Guest User

2

a guest
Apr 6th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class IntCounter
  4. {
  5. public:
  6.     IntCounter(const int* _input_count)
  7.     {
  8.         _ptr_val = _input_count;
  9.         _internal_count = new int(1); // delete where?
  10.         _total_count = new int(1);
  11.     }
  12.  
  13.     // copy ctor
  14.     // called when a new object is created from an existing object, as a copy of the existing object
  15.     IntCounter(const IntCounter& other)
  16.     {
  17.         // ako neshto = second , ++internal
  18.  
  19.         if (&other != this)
  20.         {
  21.             this->_ptr_val = other._ptr_val;
  22.             this->_total_count = other._total_count;
  23.             this->_internal_count = (other._internal_count); // ne
  24.            
  25.             ++(*this->_total_count);
  26.         }
  27.     }
  28.  
  29.  
  30.     // copy assign
  31.     // called when an already initialized object is assigned a new value from another existing object.
  32.     IntCounter& operator=(const IntCounter& other)
  33.     {
  34.         if (&other != this)
  35.         {
  36.             this->_ptr_val = other._ptr_val;
  37.             this->_total_count = other._total_count;
  38.             *this->_internal_count = (*other._total_count); // ne
  39.  
  40.             ++(*this->_total_count);
  41.         }
  42.  
  43.         return *this;
  44.     }
  45.  
  46.     ~IntCounter()
  47.     {
  48.         --(*this->_total_count);
  49.         this->_internal_count = 0;
  50.  
  51.         if ((*this->_total_count) <= 0)
  52.         {
  53.             _ptr_val = nullptr;
  54.             delete _total_count;
  55.         }
  56.     }
  57.  
  58.     int get_count() const
  59.     {
  60.         return *this->_total_count;
  61.     }
  62.  
  63. private:
  64.     const int* _ptr_val = nullptr;
  65.     int* _internal_count = nullptr;
  66.     int* _total_count = nullptr;
  67. };
  68.  
  69. int main()
  70. {
  71.     int* some_number = new int(5);
  72.     IntCounter first(some_number);
  73.     std::cout << first.get_count() << std::endl;
  74.     IntCounter second = first;
  75.     std::cout << first.get_count() << std::endl;
  76.     {
  77.         IntCounter third(second);
  78.         std::cout << first.get_count() << std::endl;
  79.     }
  80.     std::cout << first.get_count() << std::endl;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement