#include <iostream>
#include <memory>
#include <map>
using namespace std;
template<typename T>
class myShared_ptr{
public:
myShared_ptr(T* ptr = nullptr){
_ptr = ptr;
if(nullptr != ptr){
_ptrMap.insert(std::make_pair<T* &, int>(ptr, 1));
// std::make_pairs<T* &,int>(), 注意这种用法,建议用{ptr, 1}
}
}
myShared_ptr(const myShared_ptr & another){
if( nullptr != another._ptr){
_ptr = another._ptr;
_ptrMap[_ptr]++;
}
}
myShared_ptr& operator=(const myShared_ptr& another){
if (this != &another) {
if (--_ptrMap[_ptr] <= 0 && nullptr != _ptr) {
delete _ptr;
_ptr = nullptr;
_ptrMap.erase(_ptr);
}
_ptr = another._ptr;
_ptrMap[another._ptr]++;
}
return *this;
}
~myShared_ptr(){
if (--_ptrMap[_ptr] <= 0 && nullptr != _ptr) {
delete _ptr;
_ptr = nullptr;
_ptrMap.erase(_ptr);
}
}
int use_count(){
return _ptrMap[_ptr];
}
T operator*(){
return *_ptr;
}
T *operator->(){
return _ptr;
}
private:
T * _ptr;
static map<T*,int> _ptrMap;
};
template<typename T>
map<T*,int> myShared_ptr<T>::_ptrMap;
#if 0 //实现标准库的shared_ptr的功能
class Base{
public:
Base(Base*ptr){*this = *ptr;} //为了匹配第84行的代码
Base(){cout << "Base()" << endl;}
~Base(){cout << "~Base()" << endl;}
};
void func(){
myShared_ptr<Base> p1(new Base);//
myShared_ptr<Base> p2(p1);
cout << "p1: " << p1.use_count() << endl;
cout << "p2: " << p2.use_count() << endl;
//~ p2 = std::make_shared<Base>(new Base); //得自实现make_shared<>
//因为make_shared<> 返回的是 shared_ptr<>
myShared_ptr<Base> p3 = new Base;
p2 = p3;
cout << "p1: " << p1.use_count() << endl;
cout << "p2: " << p2.use_count() << endl;
cout << "p3: " << p3.use_count() << endl;
p2 = nullptr;
cout << "p1: " << p1.use_count() << endl;
cout << "p2: " << p2.use_count() << endl;
cout << "p3: " << p3.use_count() << endl;
}
#endif
#if 1 //循环引用的毛病, 待myWeak_ptr解决
class Son;
class Father{
public:
Father(){cout << "Father()" << endl;}
~Father(){cout << "~Father()" << endl;}
myShared_ptr<Son> _ptrSon;
};
class Son{
public:
Son(){cout << "Son()" << endl;}
~Son(){cout << "~Son()" << endl;}
myShared_ptr<Father> _ptrFat;
};
void func(){
myShared_ptr<Father> pF = new Father;
myShared_ptr<Son> pS = new Son;
//~ pF->_ptrSon = pS;
//~ pS->_ptrFat = pF;
}
#endif
int main(){
func();
return 0;
}