自己实现了一个菜得抠脚的shared_ptr ,
自己存草稿看看吧
template<class T>
struct Type{
typedef T type;
};
class SPCountBase{
public :
int used_count_;
void AddOne(){
used_count_++;
cout<<"add "<< used_count_<<endl;
}
void DecreaseOne(){
used_count_--;
cout<<"decreate "<< used_count_<<endl;
}
void Destory(){
delete this;
}
int used_count(){
return used_count_;
}
SPCountBase() :used_count_(1){}
virtual ~SPCountBase() { }
};
template <class T>
class CountImpl : public SPCountBase{
typedef CountImpl<T> this_type;
public :
T * px_;
CountImpl(T * p): px_(p) {
cout<<" CountImpl() "<<endl;
}
~CountImpl() {
cout << "~CountImpl()" <<endl;
delete px_;}
};
class SharedCount{ //为什么要抽象出这个count来
public:
SPCountBase * pi_;
template <class T>
SharedCount( T *p){
pi_ = new CountImpl<T>(p);
}
SharedCount( ) : pi_(){
}
~SharedCount(){
if(pi_){
pi_->DecreaseOne();
if(pi_->used_count() == 0){
delete pi_;
}
}
}
};
template <class T>
class MyShared {
public :
T * px_; //保存的是原始指针的内容
SharedCount pn_;//处理引用计数问题
MyShared (){
}
template <class X>
MyShared ( X *p) : px_(p) , pn_(p) {
}
MyShared &operator = (MyShared <T> const &r){
px_ = r.px_;
pn_.pi_ = r.pn_->pi_;
dynamic_cast< CountImpl<T> *> (pn_.pi_)->px_ =
dynamic_cast< CountImpl<T> *>(r.pn_->pi_)->px_;
pn_.pi_->AddOne();
return *this;
}
MyShared (MyShared <T> const &r){
px_ = r.px_;
pn_.pi_ = r.pn_.pi_;
dynamic_cast< CountImpl<T> *> (pn_.pi_)->px_ =
dynamic_cast< CountImpl<T> *>(r.pn_.pi_)->px_;
pn_.pi_->AddOne();
}
};
class Test{
public :
Test(){
cout<<"Test()"<<endl;
}
~Test(){
cout<<"~Test()"<<endl;
}
};
int main()
{
Test *s = new Test();
MyShared <Test> ss0(s);
MyShared <Test> ss1(ss0);
MyShared <Test> ss2(ss0);
}