weak_ptr实现
时间: 2023-06-29 13:15:55 浏览: 81
weak_ptr是C++11引入的一种智能指针,它可以用来解决shared_ptr的循环引用问题。weak_ptr指向一个shared_ptr管理的对象,但它不会增加该对象的引用计数,也不控制该对象的生命周期。如果shared_ptr被销毁了,那么weak_ptr就会变成空指针。
下面是一个简单的weak_ptr实现:
```c++
template<typename T>
class shared_ptr;
template<typename T>
class weak_ptr
{
public:
weak_ptr() : m_ptr(nullptr), m_refCount(nullptr) {}
weak_ptr(const shared_ptr<T>& sp) : m_ptr(sp.m_ptr), m_refCount(sp.m_refCount)
{
if (m_refCount)
{
m_refCount->weakCount++;
}
}
weak_ptr(const weak_ptr<T>& wp) : m_ptr(wp.m_ptr), m_refCount(wp.m_refCount)
{
if (m_refCount)
{
m_refCount->weakCount++;
}
}
~weak_ptr()
{
reset();
}
weak_ptr<T>& operator=(const shared_ptr<T>& sp)
{
reset();
m_ptr = sp.m_ptr;
m_refCount = sp.m_refCount;
if (m_refCount)
{
m_refCount->weakCount++;
}
return *this;
}
weak_ptr<T>& operator=(const weak_ptr<T>& wp)
{
reset();
m_ptr = wp.m_ptr;
m_refCount = wp.m_refCount;
if (m_refCount)
{
m_refCount->weakCount++;
}
return *this;
}
void reset()
{
if (m_refCount)
{
m_refCount->weakCount--;
if (m_refCount->weakCount == 0 && m_refCount->refCount == 0)
{
delete m_refCount;
delete m_ptr;
}
}
m_ptr = nullptr;
m_refCount = nullptr;
}
shared_ptr<T> lock() const
{
if (expired())
{
return shared_ptr<T>();
}
else
{
return shared_ptr<T>(*this);
}
}
bool expired() const
{
return use_count() == 0;
}
long use_count() const
{
if (m_refCount)
{
return m_refCount->refCount;
}
else
{
return 0;
}
}
private:
T* m_ptr;
shared_ref_count* m_refCount;
};
```
在实现中,我们需要维护一个shared_ref_count类,用来计数一个对象的引用次数和weak_ptr的数量。
```c++
class shared_ref_count
{
public:
shared_ref_count() : refCount(1), weakCount(0) {}
long refCount;
long weakCount;
};
```
在weak_ptr的构造函数中,我们需要将weakCount增加。在析构函数中,我们需要调用reset()方法,将weakCount减少,并在refCount和weakCount都为0时释放资源。
在reset()方法中,我们首先将weakCount减少,然后判断refCount和weakCount是否都为0,如果是,则释放资源。
在lock()方法中,我们首先判断是否过期(即use_count()是否为0),如果是,则返回一个空的shared_ptr,否则返回一个新的shared_ptr。
在expired()方法中,我们判断use_count()是否为0。
在use_count()方法中,我们返回refCount的值。