diff --git a/TinySTL/Memory.h b/TinySTL/Memory.h index 3629b5f..c34498c 100644 --- a/TinySTL/Memory.h +++ b/TinySTL/Memory.h @@ -112,14 +112,71 @@ namespace TinySTL{ template shared_ptr(T *p, D del) : ref_(new ref_t(p, del)){} + shared_ptr(const shared_ptr& sp){ + ref_ = sp.ref_; + ++(*ref_); + } + + shared_ptr& operator = (const shared_ptr& sp){ + if (this != &sp){ + decrease_ref(); + ref_ = sp.ref_; + } + return *this; + } + + ~shared_ptr(){ decrease_ref(); } + + element_type operator *()const{ return *(get()); } + element_type *operator ->()const{ return get(); } + element_type* get() const{ return ref_->get_data(); } size_t use_count() const{ return ref_->count(); } + + operator bool() const{ return get() != nullptr; } + private: + void decrease_ref(){ + if (ref_){ + --(*ref_); + if (use_count() == 0) + delete ref_; + } + } private: template using ref_t = Detail::ref_t < Type > ; ref_t *ref_; }; + template + bool operator == (const shared_ptr& lhs, const shared_ptr& rhs){ + return lhs.get() == rhs.get(); + } + template + bool operator == (const shared_ptr& sp, nullptr_t p){ + return sp.get() == p; + } + template + bool operator == (nullptr_t p, const shared_ptr& sp){ + return sp == p; + } + template + bool operator != (const shared_ptr& lhs, const shared_ptr& rhs){ + return !(lhs == rhs); + } + template + bool operator != (const shared_ptr& sp, nullptr_t p){ + return !(sp == p); + } + template + bool operator != (nullptr_t p, const shared_ptr& sp){ + return !(sp == p); + } + + template + shared_ptr make_shared(Args... args){ + return shared_ptr(new T(std::forward(args)...)); + } } #endif \ No newline at end of file