#include <iostream>
using namespace std;
template <typename T>
class Shared_ptr {
public:
Shared_ptr(T* p) : count(new int(1)), _ptr(p) {}
Shared_ptr(Shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {}
T* operator->() { return _ptr; }
T& operator*() { return *_ptr; }
Shared_ptr<T>& operator=(Shared_ptr<T>& other)
{
++*other.count;
if (this->_ptr && 0 == --*this->count)
{
delete count;
delete _ptr;
}
this->_ptr = other._ptr;
this->count = other.count;
return *this;
}
~Shared_ptr()
{
if (--*count == 0)
{
delete count;
delete _ptr;
}
}
int getRef() { return *count; }
private:
int* count;
T* _ptr;
};
int main(){
Shared_ptr<string> pstr(new string("abc"));
Shared_ptr<string> pstr2(pstr);
Shared_ptr<string> pstr3(new string("hao"));
pstr3 = pstr2;
cout << "share_ptr 引用个数为:" << pstr3.getRef() << endl;
return 0;
}