shared_ptr
code1
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class SmartPointer
{
public:
SmartPointer(T *p = 0) : _ptr(p), _reference_count(new size_t)
{
if (p)
*_reference_count = 1;
else
*_reference_count = 0;
}
SmartPointer(const SmartPointer &src)
{
if (this != &src)
{
_ptr = src._ptr;
_reference_count = src._reference_count;
(*_reference_count)++;
cout << "Copy. count is " << *_reference_count << endl;
}
}
SmartPointer &operator=(const SmartPointer &src)
{
if (_ptr == src._ptr)
{
cout << "== count is " << *_reference_count << endl;
return *this;
}
else
{
releaseCount();
_ptr = src._ptr;
_reference_count = src._reference_count;
(*_reference_count)++;
cout << "= count is " << *_reference_count << endl;
return *this;
}
}
T &operator*()
{
if (_ptr)
{
return *_ptr;
}
}
T *operator->()
{
if (_ptr)
{
return _ptr;
}
}
~SmartPointer()
{
cout << "Del start " << *_reference_count << endl;
if (--(*_reference_count) == 0)
{
cout << *_reference_count << " " << *_ptr << endl;
delete _ptr;
delete _reference_count;
cout << "Del." << endl;
}
}
private:
T *_ptr;
size_t *_reference_count;
void releaseCount()
{
if (_ptr)
{
(*_reference_count)--;
if ((*_reference_count) == 0)
{
delete _ptr;
delete _reference_count;
cout << "Del copy." << endl;
}
cout << "The copy ptr is exist. Count is " << *_reference_count << endl;
}
}
};
int main()
{
SmartPointer<char> cp1(new char('a'));
SmartPointer<char> cp2(cp1);
SmartPointer<char> cp3;
cout<< "-----------cp3 = cp2----"<<endl;
cp3 = cp2;
cout<< "-----------cp3 = cp1----"<<endl;
cp3 = cp1;
cout<< "-----------cp3 = cp3----"<<endl;
cp3 = cp3;
SmartPointer<char> cp4(new char('b'));
cout<< "-----------cp3 = cp4----"<<endl;
cp3 = cp4;
cout<< "-----------DEL----"<<endl;
return 0;
}
code2
#include <bits/stdc++.h>
using namespace std;
template <class T, class Del>
class SharePtr
{
public:
SharePtr(T *ptr)
: _ptr(ptr), _ref(new int(1))
{
cout << "SharePtr(T* ptr)" << endl;
}
SharePtr(SharePtr &sp)
{
cout << "SharePtr( SharePtr& sp)" << endl;
_ptr = sp._ptr;
_ref = sp._ref;
(*_ref)++;
}
~SharePtr()
{
Release();
}
void Release()
{
if (--(*_ref) == 0)
{
delete _ref;
_del(_ptr);
}
}
T *operator->()
{
return _ptr;
}
T &operator*()
{
return *_ptr;
}
SharePtr &operator=(SharePtr &sp)
{
if (_ptr != sp._ptr)
{
Release();
_ptr = sp._ptr;
_ref = sp._ref;
(*_ref)++;
}
return *this;
}
private:
T *_ptr;
int *_ref;
Del _del;
};
[1] https://blog.csdn.net/worldwindjp/article/details/18843087?depth_1-utm_source=distribute.pc_relevant_right.none-task&utm_source=distribute.pc_relevant_right.none-task
[2] https://www.cnblogs.com/wxquare/p/4759020.html