C++11的智能指针是RAII(Resource Acquisition Is Initialization)机制的一种体现。详细的介绍请参见原文原文1
对RAII的介绍请参见这里原文2
考察较多的就是shared_ptr的手写实现了,这里不是源码,只是模拟实现。
template<class T> //模板
class Share_ptr
{
// weak_ptr的friend
friend class Weak_ptr<T>; //这里先不用在意,稍后解释
public:
Share_ptr(T* _ptr) :ptr(_ptr), pCount(new int(1)) //构造
{}
Share_ptr(const Share_ptr<T>& s) // 拷贝构造
:ptr(s.ptr), pCount(s.pCount) // 这是一个指针
{
++(*pCount); //对引用计数进行++
}
~Share_ptr() //析构
{
if (*pCount == 1)
{
delete ptr;
delete pCount;
}
else
{
--(*pCount);
}
}
Share_ptr<T>& operator=(const Share_ptr<T>& s) //赋值重载
{
if (ptr != s.ptr)//排除自我拷贝
{
if (--(*pCount) == 0)
{
if (ptr)
{
delete ptr;
}
delete pCount;
}
ptr = s.ptr;
pCount = s.pCount;
++(*pCount); // 注意
}
return *this;
}
T& operator*()
{
return *ptr;
}
T* operator->()
{
return ptr;
}
private:
T* ptr;
int* pCount; //这个采用引用计数时的计数器
};
template<class T>
class Weak_ptr
{
public:
Weak_ptr(const Share_ptr<T>& s) :ptr(s.ptr) //构造
{}
T& operator*()
{
return *ptr;
}
T* operator->()
{
return ptr;
}
private:
T* ptr;
};