#include#include template class SharedPtr {public: SharedPtr() = default; explicit SharedPtr(Ty&& value); explicit SharedPtr(const Ty& value); ~SharedPtr(); SharedPtr(const SharedPtr & other); SharedPtr(SharedPtr && other); inline int use_count()noexcept { return *(this->counter); } //notice that: //当对 SharedPtr进行 *(解引用操作)的时候会调用这个先把SharedPtr转为指针. operator Ty*()noexcept; SharedPtr & operator=(const SharedPtr & other); SharedPtr & operator=(SharedPtr && other);private: mutable int* counter{ nullptr }; //引用计数. Ty* data{ nullptr }; //存储数据的指针.};template SharedPtr ::SharedPtr(Ty&& value) :data{ new Ty{std::move(value)} }, counter{ new int{0} }{ ++(*(this->counter));}template SharedPtr ::SharedPtr(const Ty& value) : data{ new Ty{value} }, counter{ new int{0} }{ ++(*(this->counter));}template SharedPtr ::SharedPtr(const SharedPtr & other) :counter{ other.counter }, data{ other.data }{ std::cout << "copy constructor" << std::endl; ++((*this->counter));}template SharedPtr ::SharedPtr(SharedPtr && other) :counter{ other.counter }, data{ std::move(other.data) }{ std::cout << "move-constructor" << std::endl; other.counter = nullptr; other.data = nullptr;}template SharedPtr & SharedPtr ::operator=(const SharedPtr & other){ std::cout << "copy operator=" << std::endl; if (*(this->counter) == 1) { delete this->data; delete this->counter; this->data = nullptr; this->counter = nullptr; }else{ --(*(this->counter)); } ++(*(other.counter)); this->counter = other.counter; this->data = other.data; return *this;}template SharedPtr & SharedPtr ::operator=(SharedPtr && other){ std::cout << "move operator=" << std::endl; this->counter = other.counter; this->data = std::move(other.data); other.counter = nullptr; other.data = nullptr; return *this;}template SharedPtr ::operator Ty*()noexcept{ std::cout << "change to ptr" << std::endl; return (this->data);}template SharedPtr ::~SharedPtr(){ --(*(this->counter)); if (*(this->counter) == 0) { delete this->counter; delete this->data; this->data = nullptr; this->counter = nullptr; }}SharedPtr func(){ SharedPtr ptr1{ 10 }; SharedPtr ptr2 = ptr1; std::cout << ptr1.use_count() << "====" << ptr2.use_count() << std::endl; return ptr2;}int main(){// SharedPtr ptr{ 20 };// std::cout << *ptr << std::endl; //先调用了 operator Ty*();// std::cout << ptr.use_count() << std::endl; std::cout << func().use_count() << std::endl; return 0;}