1. template<typename T>
    2. class SharedPtr {
    3. public:
    4. // 空构造
    5. SharedPtr() : data((T *) 0), count(0) {}
    6. // 指针构造
    7. explicit SharedPtr(T *data) : data(data), count(new int(1)) {}
    8. // 拷贝构造
    9. SharedPtr(SharedPtr<T> &other) {
    10. count = &(++(*other.count));
    11. data = other.data;
    12. }
    13. // 重载operator*和operator->实现指针功能
    14. T *operator->() { return data; }
    15. T &operator*() { return *data; }
    16. SharedPtr<T> &operator=(SharedPtr<T> const &other) {
    17. if (this == &other) return *this;
    18. ++(*other.count);
    19. if (this->data && --(*this->count) == 0) {
    20. delete data;
    21. delete count;
    22. std::cout << "delete ptr =" << std::endl;
    23. }
    24. this->count = other.count;
    25. this->data = other.data;
    26. return *this;
    27. }
    28. virtual ~SharedPtr() {
    29. if (data && --(*count) == 0) {
    30. delete data;
    31. delete count;
    32. std::cout << "delete ptr~" << std::endl;
    33. }
    34. }
    35. int getRef() {
    36. return *count;
    37. }
    38. private:
    39. T *data;
    40. int *count;
    41. };
    42. int main() {
    43. SharedPtr<std::string> ptr(new std::string("a2"));
    44. std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl;
    45. SharedPtr<std::string> pstr2(ptr);
    46. std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl;
    47. std::cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << std::endl;
    48. SharedPtr<std::string> pstr3(new std::string("b3"));
    49. std::cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << std::endl;
    50. pstr3 = pstr2;
    51. std::cout << "ptr:" << ptr.getRef() << " " << *ptr << std::endl;
    52. std::cout << "pstr2:" << pstr2.getRef() << " " << *pstr2 << std::endl;
    53. std::cout << "pstr3:" << pstr3.getRef() << " " << *pstr3 << std::endl;
    54. return 0;
    55. }