template <typename T>
class SharedPtr{
public:
SharedPtr() = delete;
SharedPtr(const SharedPtr&) noexcept;
SharedPtr(T*) noexcept;
SharedPtr& operator=(const SharedPtr<T>) noexcept;
T& operator*() noexcept;
T* operator->() noexcept;
~SharedPtr();
private:
T *ptr;
int *use_count;
};
template <typename T>
SharedPtr<T>::SharedPtr(T* ptr) noexcept:ptr(ptr), use_count(new int(1))
{}
template <typename T>
SharedPtr<T>::SharedPtr(const SharedPtr &s_ptr) noexcept {
ptr =s_ptr.ptr;
use_count = s_ptr.use_count;
++(*use_count);
}
template <typename T>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr<T> rhs) noexcept {
if(rhs.ptr == this->ptr){
return *this;
}
++(*rhs.use_count);
if(0 == --(use_count)){
delete ptr;
delete use_count;
std::cout << "deconstruct" << std::endl;
}
ptr = rhs.ptr;
use_count = rhs.use_count;
return *this;
}
template <typename T>
T& SharedPtr<T>::operator*() noexcept{
return *this->ptr;
}
template <typename T>
T* SharedPtr<T>::operator->() noexcept{
return this->ptr;
}
template <typename T>
SharedPtr<T>::~SharedPtr(){
if(0 == --(*use_count)){
delete ptr;
delete use_count;
}
}