以下实现未考虑线程安全性,原理很简单,关键地方给了注释,很容易看懂。
unique_ptr的实现:
#include<iostream>
#define boolinfo(x) ((x)?"true":"false") //方便输出布尔信息
using namespace std;
template<typename T>
class Unique_ptr
{
public:
~Unique_ptr(){delete m_ptr;}
Unique_ptr(T* ptr=nullptr):m_ptr(ptr){}
//删除拷贝构造和拷贝赋值
Unique_ptr(const Unique_ptr&)=delete;
Unique_ptr& operator=(const Unique_ptr&)=delete;
//增加移动构造和移动赋值
Unique_ptr(Unique_ptr&& rhs)noexcept
{
m_ptr = rhs.m_ptr;
rhs.m_ptr = nullptr;
}
Unique_ptr& operator=(Unique_ptr&& rhs)noexcept
{
if(this == &rhs)return *this;
m_ptr = rhs.m_ptr;
rhs.m_ptr = nullptr;
return *this;
}
//为了让它表现的像指针,要实现以下三个函数
T& operator*()const{return *m_ptr;}
T* operator->()const{return m_ptr;}
operator bool()const{return m_ptr;}
private:
T* m_ptr;
};
//测试类型
class Type
{
public:
Type(int i=2):m_i(i){}
int m_i;
};
int main()
{
Unique_ptr<Type> t(new Type(4));
Unique_ptr<Type> t2(move(t));
Unique_ptr<Type> t3;
t3 = move(t2);
cout << t3->m_i << endl;
cout << boolinfo(t) << endl;
cout << boolinfo(t2) << endl;
cout << boolinfo(t3) << endl;
return 0;
}
//输出结果如下:
4
false
false
true
shared_ptr的实现:
#include<iostream>
#define boolinfo(x) ((x)?"true":"false") //方便输出布尔信息
using namespace std;
//测试类型
class Type
{
public:
Type(int t=1): a(t){}
int a = 1;
};
template<typename T>
class Shared_ptr
{
public:
typedef size_t count_type;
~Shared_ptr()
{
//当引用计数为0时,释放资源
if(!m_share_count->reduce_count())
{
delete m_share_count;//释放引用计数器
delete m_ptr;//释放所管理的指针
cout << "m_ptr deleted~" << endl;
}
}
Shared_ptr(T* ptr=nullptr):m_ptr(ptr)
{
if(m_ptr)//非nullptr指针才会设置引用计数器
{
m_share_count = new share_count;
}
}
Shared_ptr(const Shared_ptr& rhs):m_ptr(rhs.m_ptr),
m_share_count(rhs.m_share_count)
{
//只有非nullptr指针的m_share_count才是有效的
if(m_ptr)m_share_count->add_count();
}
Shared_ptr& operator=(const Shared_ptr& rhs)
{
//首先检查是不是自己给自己赋值
if(this == &rhs)return *this;
//然后判断是否需要释放原来的资源
if(!m_share_count->reduce_count())
{
delete m_share_count;
delete m_ptr;
}
//复制资源
m_ptr = rhs.m_ptr;
m_share_count = rhs.m_share_count;
//只有非nullptr指针的m_share_count才是有效的,才需要增加引用计数
if(m_ptr)m_share_count->add_count();
return *this;
}
//为了让智能指针表现的像指针,需要实现以下三个函数
T& operator*()const{return *m_ptr;}
T* operator->()const{return m_ptr;}
operator bool()const{return m_ptr;}
//获取当前的引用计数个数
count_type use_count()const{return m_share_count->get_count();}
private:
//负责引用计数的类
class share_count
{
public:
share_count():m_count(1){}
void add_count(){++m_count;}
count_type reduce_count(){return --m_count;}
count_type get_count()const{return m_count;}
private:
count_type m_count;
};
private:
T* m_ptr;//管理的指针
share_count* m_share_count;//引用计数器
};
int main()
{
Shared_ptr<Type> t(new Type(3));
cout << "t's share_count is: " << t.use_count() << endl;
Shared_ptr<Type> t2(t);
cout << "t's share_count is: " << t.use_count() << endl;
Shared_ptr<Type> t3(t);
cout << "t's share_count is: " << t.use_count() << endl;
return 0;
}
输出结果如下:
t's share_count is: 1
t's share_count is: 2
t's share_count is: 3
m_ptr deleted~
以上内容参考自C++手把手带你实现一个智能指针