前言
众所周知,智能指针其实也是模板类,智能指针实现内存分配和释放就是通过构造函数和析构函数实现的,接下来就简单说明一下shared_ptr的实现原理。
实现原理
- shared_ptr由于允许多个对象指向同一对象,所以拷贝构造和拷贝复制肯定是存在且需要定义的。
- shared_ptr又是如何判断是否可以释放内存呢?根据之前的文章可以知道,是通过一个引用计数来实现的,所以我们需要一个能够用来记录指针个数的成员变量,而单纯的int无法同步多个shared_ptr的值,所以我们最好采用int*类型的成员变量。
- 而智能指针本质就是指针,所以我们还需要利用模板来实现一个多种类型的成员指针。
代码实现
//shared_ptr的构造
#include<iostream>
#include<memory>
using namespace std;
template<typename T>
class Shared_ptr
{
public:
Shared_ptr(T* ptr=NULL):count(new int (1)),ptr_(ptr){
cout<<"构造"<<endl;
}
Shared_ptr(const Shared_ptr<T>& s):count(s.count),ptr_(s.ptr_){
cout<<"拷贝构造"<<endl;
// ++(*s.count);
(*count) ++;
}
Shared_ptr<T> operator=(const Shared_ptr<T>& s){
if(this!=&s){
if(--(*(this->count))==0){
delete this->count;
this->count=nullptr;
delete this->ptr_;
this->ptr_=nullptr;
}
cout<<"拷贝赋值"<<endl;
ptr_=s.ptr_;
count=s.count;
++*(count);
// ++*(s.count);
}
}
int use_count()
{
return * count;
}
~Shared_ptr()
{
--(*(this->count));
if(*(this->count)==0)
{
delete this->count;
this->count=nullptr;
delete this->ptr_;
this->ptr_=nullptr;
}
}
private:
int* count;
T* ptr_;
};
int main()
{
int* t=new int(1);
Shared_ptr<int> p(t);
Shared_ptr<int>q=p;
cout<<p.use_count()<<endl;
cout<<q.use_count()<<endl;
shared_ptr<int>p1=make_shared<int>(1);
shared_ptr<int>q1=p1;
cout<<p1.use_count()<<endl;
cout<<q1.use_count()<<endl;
return 0;
}