Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class IntCounter
- {
- public:
- IntCounter(const int* _input_count)
- {
- _ptr_val = _input_count;
- _internal_count = new int(1); // delete where?
- _total_count = new int(1);
- }
- // copy ctor
- // called when a new object is created from an existing object, as a copy of the existing object
- IntCounter(const IntCounter& other)
- {
- // ako neshto = second , ++internal
- if (&other != this)
- {
- this->_ptr_val = other._ptr_val;
- this->_total_count = other._total_count;
- this->_internal_count = (other._internal_count); // ne
- ++(*this->_total_count);
- }
- }
- // copy assign
- // called when an already initialized object is assigned a new value from another existing object.
- IntCounter& operator=(const IntCounter& other)
- {
- if (&other != this)
- {
- this->_ptr_val = other._ptr_val;
- this->_total_count = other._total_count;
- *this->_internal_count = (*other._total_count); // ne
- ++(*this->_total_count);
- }
- return *this;
- }
- ~IntCounter()
- {
- --(*this->_total_count);
- this->_internal_count = 0;
- if ((*this->_total_count) <= 0)
- {
- _ptr_val = nullptr;
- delete _total_count;
- }
- }
- int get_count() const
- {
- return *this->_total_count;
- }
- private:
- const int* _ptr_val = nullptr;
- int* _internal_count = nullptr;
- int* _total_count = nullptr;
- };
- int main()
- {
- int* some_number = new int(5);
- IntCounter first(some_number);
- std::cout << first.get_count() << std::endl;
- IntCounter second = first;
- std::cout << first.get_count() << std::endl;
- {
- IntCounter third(second);
- std::cout << first.get_count() << std::endl;
- }
- std::cout << first.get_count() << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement