智能指针
-
智能指针的使用:
模拟C++11中的shared_ptr实现一个智能指针,包含初始化,拷贝,赋值等操作。
采用引用计数的方式来控制指针的析构。 -
类的定义
template<typename T>
class MySmartPoint
{
T* m_ptr;
size_t* ref_count = 0;
public:
MySmartPoint(T* ptr = nullptr);
~MySmartPoint();
MySmartPoint(const MySmartPoint& s_point);
MySmartPoint& operator=(const MySmartPoint& s_point);
size_t GetCount();
T& operator*();
T* operator->();
};
- 类的实现
智能指针的构造函数和析构函数
template<typename T>
inline MySmartPoint<T>::MySmartPoint(T* ptr)
:m_ptr(ptr)
,ref_count(new size_t(1))
{
}
template<typename T>
inline MySmartPoint<T>::~MySmartPoint()
{
if (--(*ref_count) == 0)
{
delete m_ptr;
delete ref_count;
m_ptr = nullptr;
ref_count = nullptr;
std::cout << "引用为0,调用析构函数" << endl;
}
}
智能指针的拷贝构造和赋值运算符
template<typename T>
MySmartPoint<T>::MySmartPoint(const MySmartPoint& s_point)
{
if (this != &s_point)
{
this->m_ptr = s_point.m_ptr;
this->ref_count = s_point.ref_count;
++(*this->ref_count);
}
}
template<typename T>
MySmartPoint<T>& MySmartPoint<T>::operator=(const MySmartPoint& s_point)
{
if(m_ptr == s_point.m_ptr)
{
return *this;
}
else
{
if (--(*ref_count) == 0)
{
delete m_ptr;
delete ref_count;
m_ptr = nullptr;
ref_count = nullptr;
std::cout << "引用为0,调用析构函数" << endl;
}
m_ptr = s_point.m_ptr;
ref_count = s_point.ref_count;
++(*ref_count);
return *this;
}
}
智能指针引用计数和 *,->的重载
template<typename T>
size_t MySmartPoint<T>::GetCount()
{
return *ref_count;
}
template<typename T>
inline T& MySmartPoint<T>::operator*()
{
if (this->m_ptr)
{
return *m_ptr;
}
}
template<typename T>
inline T* MySmartPoint<T>::operator->()
{
if (this->m_ptr)
{
return m_ptr;
}
}
测试程序
#include <iostream>
#include "MySmartPoint.h"
using namespace std;
int main()
{
MySmartPoint<int> p(new int());
MySmartPoint<int> q(p);
MySmartPoint<int> x;
*p = 10;
cout << p.GetCount() << endl;
cout << *p << endl;
p = x;
cout << x.GetCount() << endl;
q = x;
cout << q.GetCount() << endl;
cout << x.GetCount() << endl;
{
MySmartPoint<int> c;
}
system("pause");
return 0;
}
运行结果