shared_ptr概述
shared_ptr是C++11中提供的一个智能指针类,可以在任何位置都不使用时自动删除指针,从而彻底消除内存泄露和悬空指针问题。它在设计过程中遵循共享所有权的概念,即不同的shared_ptr可以引用同一个指针,并在内部使用计数器机制来实现这一点。
每个 shared_ptr 对象在内部指向两个内存位置:
- 指向对象的指针。
- 用于控制引用计数数据的指针。
共享所有权如何在参考计数的帮助下工作:
- 当新的 shared_ptr 对象与指针关联(复制构造,赋值等)时,则在其构造函数中,将与此指针关联的引用计数增加1。
- 当任何 shared_ptr 对象超出作用域时,则在其析构函数中,它将关联指针的引用计数减1。
- 如果引用计数变为0,则表示没有其他 shared_ptr 对象与此内存关联,在这种情况下,它使用delete函数删除该内存。
shared_ptr数据结构
为了实现共享所有权功能,我们采用如下的数据结构来完成。
class smart{
private:
T* _ptr;
int* _count;
...
};
shared_ptr主要模块
smart(T* ptr = nullptr)
smart(const smart& ptr)
smart& operator=(const smart& ptr)
T& operator*()
T& operator->()
~smart()
int use_count()
模块结构图如下:
代码实现
#include <memory>
#include<iostream>
using namespace std;
template<typename T>
class smart
{
private:
T* _ptr;
int* _count;
public:
smart(T* ptr = nullptr) :_ptr(ptr)
{
if (_ptr)
{
_count = new int(1);
}
else
{
_count = new int(0);
}
}
smart(const smart& ptr)
{
if (this != &ptr)
{
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count)++;
}
}
smart& operator=(const smart& ptr)
{
if (this->_ptr == ptr._ptr)
{
return *this;
}
if (this->_ptr)
{
(*this->_count)--;
if (this->_count == 0)
{
delete this->_ptr;
delete this->_count;
}
}
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count)++;
return *this;
}
//operator*重载
T& operator*()
{
if (this->_ptr)
{
return *(this->_ptr);
}
}
//operator->重载
T& operator->()
{
if (this->_ptr)
{
return this->_ptr;
}
else
{
return nullptr;
}
}
//析构函数
~smart()
{
(*this->_count)--;
if (*this->_count == 0)
{
delete this->_ptr;
delete this->_count;
}
}
//return reference couting
int use_count()
{
return *this->_count;
}
};
int main()
{
smart<int> sm(new int(10));
cout << "operator*():" << *sm << endl;
cout << "reference couting:(sm)" << sm.use_count() << endl;
smart<int> sm2(sm);
cout << "copy ctor reference couting:(sm)" << sm.use_count() << endl;
smart<int> sm3;
sm3 = sm;
cout << "copy operator= reference couting:(sm)" << sm.use_count() << endl;
cout << &sm << endl;
return 0;
}