实现:
template <typename T>
class Shared_ptr {
public:
Shared_ptr() :_count(nullptr), _ptr(nullptr) {}
Shared_ptr(T* ptr) :_count(new int(1)), _ptr(ptr) {}
Shared_ptr(Shared_ptr<T>& sptr) : _count(&(++* sptr._count)), _ptr(sptr._ptr) {}
T* operator->() { return _ptr; }
T& operator*() { return *_ptr; }
int getRef() { return *_count; }
Shared_ptr<T>& operator=(Shared_ptr<T>& other) {
if (this == &other)
return *this;
if (this->_ptr && --*this->_count == 0) {
delete _count;
delete _ptr;
cout << "delete ptr!" << endl;
}
++*other._count;
this->_ptr = other._ptr;
this->_count = other._count;
return *this;
}
~Shared_ptr() {
if (_ptr && -- *_count == 0) {
delete _count;
delete _ptr;
cout << "delete ptr!" << endl;
}
}
private:
T* _ptr;
int* _count;
};
测试代码:
#define name(x) #x
#define PrintPtr(ptr) cout << name(ptr) << " " << "count: " << ptr.getRef() << " " << "data: " << *ptr << endl;
int main() {
Shared_ptr<string> strptr1(new string("abc"));
PrintPtr(strptr1);
Shared_ptr<string> strptr2(strptr1);
PrintPtr(strptr1);
PrintPtr(strptr2);
Shared_ptr<string> strptr3(new string("hao"));
PrintPtr(strptr3);
strptr3 = strptr2;
PrintPtr(strptr1);
PrintPtr(strptr2);
PrintPtr(strptr3);
}