总结一下今天所学的shared_ptr
shared_ptr与scoped_ptr一样包装了new操作符在堆上分配的动态对象,区别在于它是应用技术型的智能指针,可以被自由地拷贝与赋值,在任何地方都可以共享。
//主函数test.cpp
#include<iostream>
using namespace std;
//#include<memory>
#include"shared_ptr.h"void main()
{
int *p = new int(10);
shared_ptr<int> pa(p);//1调用类shared_ptr
cout<<"*pa"<<*pa<<endl;
cout<<"count = "<<pa.count()<<endl;
shared_ptr<int> ps1=pa;
cout<<*pa<<endl;
cout<<"use_count = "<<pa.count()<<endl;
//类shared_ptr头文件
#ifndef _SHARED_PTR_H
#define _SHARED_PTR_H
#include<iostream>
using namespace std;
#include"shared_count.h"
template<class T>
class shared_ptr
{
public:
shared_ptr(T* p):px(p),pn(px)
{
#ifdef DISPLAY
cout<<"create shared_ptr."<<endl;
#endif
}
~shared_ptr()
{
#ifdef DISPLAY
cout<<"free shared_ptr."<<endl;
#endif
}
public:
long count()const
{
return pn.count();
}
bool unique()const
{
return pn.count==0;
}
T& operator*()
{
return *px;
}
T* operator->()
{
return px;
}
private:
T* px;
shared_count pn;//2调用类shared_count
};
//类shared_count头文件
#ifndef _SHARED_COUNT_H
#define _SHARED_COUNT_H
#include<iostream>
#include"sp_shared_base.h"//基类
#include"sp_count_impl_xx.h"//共享指针实现类
using namespace std;
class shared_count //引用计数类
{
public:
template<class Y>
shared_count(Y* p):pi_(new sp_count_impl_xx<Y> (p))//3调用实现类sp_count_impl_xx 将主函数p的值传入实现类中 //即px_指向p(10)地址空间
{
#ifdef DISPLAY
cout<<"create shared_count."<<endl;
#endif
}
shared_count(const shared_count &r):pi_(r.pi_)
{
if(pi_!=0)
{
pi_->add_ref_count();
}
}
~shared_count()
{
#ifdef DISPLAY
cout<<"free shared_count."<<endl;
#endif
}
long count()const
{
return pi_!=0?pi_->count():0;
}
private:
sp_shared_base *pi_;
};
#endif
//实现类sp_count_impl_xx头文件
#ifndef _SP_COUNT_IMPL_XX_H
#define _SP_COUNT_IMPL_XX_H
#include "sp_shared_base.h"
template <class T>
class sp_count_impl_xx:public sp_shared_base//4继承基类 先调用基类sp_shared_base
{
public:
sp_count_impl_xx(T* p):px_(p)
{
#ifdef DISPLAY
cout<<"create sp_count_impl_xx."<<endl;
#endif
}
~sp_count_impl_xx()
{
#ifdef DISPLAY
cout<<"free sp_count_impl_xx."<<endl;
#endif
}
private:
T* px_;
};
#endif
//基类sp_shared_base头文件
#ifndef _SP_SHARED_BASE_H
#define _SP_SHARED_BASE_H
#include<iostream>
using namespace std;
class sp_shared_base //共享指针的基类
{
public:
sp_shared_base():count_(1)
{
#ifdef DISPLAY
cout<<"create sp_shared_base."<<endl;
#endif
}
sp_shared_base(sp_shared_base &p)
{
p.count_ = 1;
}
~sp_shared_base()
{
#ifdef DISPLAY
cout<<"free sp_shared_base."<<endl;
#endif
}
long count()const
{
return count_;
}
void add_ref_count()
{
++count_;
}
private:
long count_;
};
#endif
//运行顺序为: create sp_shared_base,
create sp_count_impl.
create shared_count.
create shared_ptr.
free shared_ptr.
free shared_count.//存在内存泄露问题!!