如果对shared_ptr是什么不是很清楚,可以百度或是参考C++primer等参考书。
文章只是对其进行了一个简单实现,来模拟shared_ptr的功能。
实现方式是添加了一层中间的节点。如下图所示
具体代码实现如下:
#include<iostream>
using namespace std;
template<class T>
class SmartPtr;
template<class T>
class Uptr
{
private:
typedef T valueType;
typedef T* valuePtr;
friend class SmartPtr<valueType>;
private:
//construct function
Uptr(valuePtr ps) :p(ps)
{
count = 1;
}
~Uptr()
{
delete p;
}
private:
valuePtr p;
unsigned count;
};
template<class T>
class SmartPtr
{
public:
typedef T valueType;
typedef T* valuePtr;
public:
SmartPtr(valuePtr p) :uptr(new Uptr<valueType>(p))
{}
~SmartPtr()
{
deconstruct();
}
SmartPtr(const SmartPtr<valueType>& sp):uptr(sp.uptr)
{
//uptr = sp.uptr;
uptr->count++;
cout << "Used SmartPtr(const SmartPtr&)" << endl;
cout << "-----Have " << uptr->count << "ptr ref this!" << endl;
}
SmartPtr& operator=(const SmartPtr<valueType>& sp)
{
--uptr->count;
if (uptr->count == 0)
deconstruct();
uptr = sp.uptr;
++uptr->count;
cout << "Used SmartPtr& operator=(const SmartPtr&)" << endl;
cout << "-----Have " << uptr->count << "ptr ref this!" << endl;
return *this;
}
valueType& operator* ()
{
return *(uptr->p);
}
valuePtr operator->()
{
return &(operator*());
}
private:
void deconstruct()
{
--uptr->count;
if (uptr->count == 0)
{
delete uptr;
}
else
cout << "Still have " << uptr->count << " ptr ref this val !";
}
private:
Uptr<valueType> *uptr;
};
int main()
{
int i = 0;
SmartPtr<int> p(&i);
SmartPtr<int> kk = p;
{
SmartPtr<int> k = p;
}
SmartPtr<int> z = p;
return 0;
}
运行效果图如下: