template<typename T>class SharedPtr {public: // 空构造 SharedPtr() : data((T *) 0), count(0) {} // 指针构造 explicit SharedPtr(T *data) : data(data), count(new int(1)) {} // 拷贝构造 SharedPtr(SharedPtr<T> &other) { count = &(++(*other.count)); data = other.data; } // 重载operator*和operator->实现指针功能 T *operator->() { return data; } T &operator*() { return *data; } SharedPtr<T> &operator=(SharedPtr<T> const &other) { if (this == &other) return *this; ++(*other.count); if (this->data && --(*this->count) == 0) { delete data; delete count; std::cout << "delete ptr =" << std::endl; } this->count = other.count; this->data = other.data; return *this; } virtual ~SharedPtr() { if (data && --(*count) == 0) { delete data; delete count; std::cout << "delete ptr~" << std::endl; } } int getRef() { return *count; }private: T *data; int *count;};int main() { SharedPtr<std::string> ptr(new std::string("a2")); std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl; SharedPtr<std::string> pstr2(ptr); std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl; std::cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << std::endl; SharedPtr<std::string> pstr3(new std::string("b3")); std::cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << std::endl; pstr3 = pstr2; std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl; std::cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << std::endl; std::cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << std::endl; return 0;}