/* * smart_pointer.h Smart pointer, Step 2. * * Operators for negation (!), equality (==), and inequality (!=) have * been added, in several specialized forms. */ #ifndef SMARTPOINTER_H #define SMARTPOINTER_H #include namespace IDA_Smart_Pointer { class smart_pointer { public: smart_pointer() = default; explicit smart_pointer(int* p) : ptr_{ p } {} smart_pointer(const smart_pointer& other) { copy(other); } smart_pointer(smart_pointer&& other) noexcept { swap(other); } ~smart_pointer() { delete ptr_; } smart_pointer& operator=(const smart_pointer& rhs) & { smart_pointer{ rhs }.swap(*this); return *this; } smart_pointer& operator=(smart_pointer&& rhs) & noexcept { if (this != &rhs) { clear(); swap(rhs); } return *this; } smart_pointer& operator=(int* rhs) { smart_pointer{ rhs }.swap(*this); return *this; } int& operator*() { return *ptr_; } int* operator->() { return ptr_; } bool operator!() const { return ptr_ == nullptr; } friend bool operator==(const smart_pointer& lhs, const smart_pointer& rhs); friend bool operator==(const smart_pointer& lhs, const int* rhs); friend bool operator==(const int* lhs, const smart_pointer& rhs); friend bool operator!=(const smart_pointer& lhs, const smart_pointer& rhs); friend bool operator!=(const smart_pointer& lhs, const int* rhs); friend bool operator!=(const int* lhs, const smart_pointer& rhs); void swap(smart_pointer& other) { std::swap(ptr_, other.ptr_); } private: int* ptr_{ nullptr }; void copy(const smart_pointer& p) { ptr_ = (p.ptr_ != nullptr) ? new int{ *p.ptr_ } : nullptr; } void clear() { delete ptr_; ptr_ = nullptr; } }; void swap(smart_pointer& x, smart_pointer& y); bool operator==(const smart_pointer& lhs, const smart_pointer& rhs); bool operator==(const smart_pointer& lhs, const int* rhs); bool operator==(const int* lhs, const smart_pointer& rhs); bool operator!=(const smart_pointer& lhs, const smart_pointer& rhs); bool operator!=(const smart_pointer& lhs, const int* rhs); bool operator!=(const int* lhs, const smart_pointer& rhs); } // namespace IDA_Smart_Pointer #endif