sp_counted_base.h
#pragma once
class sp_counted_base//管理对象引用计数
{
public:
sp_counted_base() :count(1)
{
}
void add()
{
count++;
}
void dec()
{
count--;
}
int getcount()
{
return count;
}
virtual void realse() = 0;
private:
int count;
};
sp_counted_impl.h
#include "sp_counted_base.h"
template<typename T>
class sp_counted_impl : public sp_counted_base//管理对象释放
{
public:
sp_counted_impl(T *p=NULL) :px(p){}
void realse()
{
dec();
if (getcount() == 0)
{
if (px != NULL)
{
cout << "free" << endl;
delete px;
px = NULL;
}
}
}
private:
T *px;
};
shared_count.h
#pragma once
#include "sp_counted_base.h"
#include "sp_counted_impl.h"
template<typename T>
class shared_count
{
public:
shared_count(T *ptr=NULL):pi(new sp_counted_impl<T>(ptr))
{}
shared_count(const shared_count &sc)
{
pi = sc.pi;
pi->add();
}
shared_count& operator=(const shared_count& sc)
{
if (this != &sc)
{
pi = sc.pi;
pi->add();//引用计数加1。
}
return *this;
}
~shared_count()
{
realse();
}
void realse()
{
pi->realse();
}
void add()
{
pi->add();
}
private:
sp_counted_base *pi;
};
share_ptr.h
#pragma once
#include "shared_count.h"
template<typename T>
class shared_ptr//对象操作。
{
public:
shared_ptr(T *ptr = NULL) :px(ptr), pn(ptr)
{}
shared_ptr(const shared_ptr& sp)
{
px = sp.px;
pn = sp.pn;
}
shared_ptr& operator = (const shared_ptr& sp)
{
if (this != &sp)
{
pn.realse();//释放它原来所指的对象的引用。
pn = sp.pn;//计数重载=,在shared_count.h中实现。
px = sp.px;//重新指向对象。
}
return *this;
}
~shared_ptr()
{
}
T* operator->()
{
return px;
}
T& operator*()
{
return *px;
}
private:
T *px;
shared_count<T> pn;
};
main.cpp//测试代码
#include <iostream>
#include "shared_ptr.h"
using namespace std;
int main()
{
shared_ptr<int> ps(new int(1));
shared_ptr<int> pb(ps);
shared_ptr<int> pd(pb);
shared_ptr<int> pq(pd);
shared_ptr<int> pm(new int(2));
pm = pq;
return 0;
}
未涉及线程安全,未涉及weak_ptr,未涉及boost库里面的定置删除器/定置分配器。