#pragma once #include namespace smart_pointer { class exception : std::exception { using base_class = std::exception; using base_class::base_class; }; template class SmartPointer { ENABLE_CLASS_TESTS; public: using value_type = T; explicit SmartPointer(value_type* x = nullptr) { if (x == nullptr) { this->core = nullptr; } else { this->core = new Core(x, 1); } } SmartPointer(const SmartPointer& x) { if (x.core != nullptr) { this->core->ref_count++; } this->core = x.core; } SmartPointer(SmartPointer&& x) { this->core = x.core; x.core = nullptr; } SmartPointer& operator=(const SmartPointer& x) { ~SmartPointer(); this->core = x.core; if (x.core != nullptr) { this->core->ref_count++; } return *this; } SmartPointer& operator=(SmartPointer&& x) { ~SmartPointer(); this->core = x.core; x.core = nullptr; return *this; } SmartPointer& operator=(value_type* x) { ~SmartPointer(); if (x != nullptr) { this->core = new Core(x, 1); } else { this->core = nullptr; } return *this; } ~SmartPointer() { if (this->core != nullptr) { this->core->ref_cout--; if (this->core->ref_cout == 0) { delete (this->core); } } } value_type& operator*() { if (this->core == nullptr) { throw smart_pointer::exception(); } else { return *(this->core->ptr); } } const value_type& operator*() const { if (this->core == nullptr) { throw smart_pointer::exception(); } else { return *(this->core->ptr); } } value_type* operator->() const { if (this->core == nullptr) { return nullptr; } else { return core->ptr; } } value_type* get() const { if (this->core == nullptr) { return nullptr; } else { return this->core->ptr; } } operator bool() const { return this->core != nullptr; } template bool operator==(const SmartPointer& pointer) const { return static_cast(this->get()) == static_cast(pointer.get()); } template bool operator!=(const SmartPointer& pointer) const { return static_cast(this->get()) != static_cast(pointer.get()); } std::size_t count_owners() const { if (this->core != nullptr) { return this->core->ref_count; } else { return 0; } } private: class Core { public: std::size_t ref_count; value_type* ptr; Core() { } Core(value_type* ptr, std::size_t ref_count) : ptr(ptr), ref_count(ref_count) { } ~Core() { Allocator allocator; allocator.deallocate(ptr, sizeof(value_type)); this->ptr = nullptr; } }; Core* core; }; } // namespace smart_pointer #endif