实现一个简单的shared_ptr
需要考虑以下几点:
- 构造函数中计数初始化为1;
- 拷贝构造函数中计数值加1;
- 赋值运算符中,左边的对象引用计数减1,右边的对象引用计数加1;
- 析构函数中引用计数减1;
- 在赋值运算符和析构函数中,如果减1后为0,则调用delete释放对象。
代码如下:
template <class T>
class shared_ptr {
private:
T* ptr_;
// 计数指针,如果用对象,每次初始化之后都是新的值;如果用static,则不同的智能指针会拥有相同的count
int* pCount_;
public:
// 构造函数
shared_ptr(T* p) : ptr_(p), pCount_(new int(1)) {
}
// 拷贝构造
shared_ptr(shared_ptr& another) {
ptr_ = another.ptr_;
pCount = another.pCount_;
++(*pCount);
}
// 重载*操作符
T& operator *() {
return *ptr_;
}
// 重载->操作符
T* operator ->() {
return ptr_;
}
// 获取引用计数
int getCount() {
return *pCount_;
}
// 析构
~shared_ptr() {
(*pCount_)--;
if (0 == *pCount_) {
delete ptr_;
delete pCount_;
}
}
};