转载:面试时实现智能指针
#include<iostream>
#include<cstdio>
using namespace std;
template<typename T>
class SmartPointer
{
public:
//构造函数
SmartPointer(T* ptr)
{
ref = ptr;
ref_count = (unsigned int*)malloc(sizeof(unsigned));
*ref_count = 1;
}
//拷贝构造函数
SmartPointer(const SmartPointer<T>& other)
{
ref = other.ref;
ref_count = other.ref_count;
++*ref_count;//引用计数增加
}
//赋值运算符重载
SmartPointer& operator=(SmartPointer<T>& other)
{
if (this == &other)
return *this;
//引用计数为0时调用析构
if (--*ref_count == 0)
{
clear();
}
ref = other.ref;
ref_count = other.ref_count;
++*ref_count;
return *this;
}
//取地址
T& operator*()
{
return *ref;
}
//取值
T* operator->()
{
return ref;
}
//析构函数
~SmartPointer()
{
if (--*ref_count == 0)
{
clear();
}
}
private:
//析构处理
void clear()
{
delete ref;
free(ref_count);
ref = NULL;
ref_count = NULL;
}
protected:
T* ref;//指针
unsigned int* ref_count;//引用计数
};
void main()
{
int* p = new int();
*p = 11;
SmartPointer<int> ptr1(p);
SmartPointer<int> ptr2 = ptr1;
*ptr1 = 1;
cout << *ptr1 << " " << *ptr2 << endl;
}