template<typename T>
class SharedPointer {
public:
SharedPointer(T *ptr = nullptr) : _ptr(ptr){
if(ptr != nullptr)
_count = new int(1);
else
_count = new int(0);
}
// 拷贝构造函数
SharedPointer(const SharedPointer& ptr){
if(this != &ptr){
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count) ++;
}
}
// 拷贝赋值运算符
SharedPointer& operator = (const SharedPointer &ptr){
if(this->_ptr == ptr._ptr){
return *this;
}
if(this->_ptr){
(*this->_count) --;
if((*this->_count) == 0){
delete this->_count;
delete this->_ptr;
}
}
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count) ++;
return *this;
}
~SharedPointer(){
(*this->_count) --;
if((*this->_count) == 0){
delete this->_count;
delete this->_ptr;
}
}
public:
T& operator*(){
return *(this->_ptr);
}
T* operator->(){
return this->_ptr;
}
int use_count(){
return *(this->_count);
}
T* get(){
return this->_ptr;
}
// 重载布尔值操作
operator bool(){
return this->_ptr == nullptr;
}
private:
T *_ptr;
int *_count;
};
// 测试代码
void testSharedPointer(){
SharedPointer<int> p1(new int(10));
cout << "值:" << *(p1.get()) << " 引用计数:" << p1.use_count() << endl;
*p1 = 100;
cout << "值:" << *p1 << " 引用计数:" << p1.use_count() << endl;
{
SharedPointer<int> p2(p1);
*p2 = 3;
cout << "值:" << *p2 << " 引用计数:" << p1.use_count() << endl;
SharedPointer<int> p3 = p2;
*p3 = 55;
cout << "值:" << *p3 << " 引用计数:" << p1.use_count() << endl;
cout << "值:" << *p2 << " 引用计数:" << p1.use_count() << endl;
}
cout << "值:" << *p1 << " 引用计数:" << p1.use_count() << endl;
if(p1){
cout << "True" << endl;
}
SharedPointer<string> q1(new string("我是string1"));
cout << "值:" << (*(q1)).c_str() << " size:" << q1->size() << endl;
}