// smart pointer implements
#include <iostream>
#include <memory>
using namespace std;
template<typename T> class SharePtr;
template<typename T>
class ResPtr { // manage res of memory
private:
T* res_p; // point res
int use_num; // count
ResPtr(T *p) : res_p(p), use_num(1){
cout << "the constructor of ResPtr\n";
}
~ResPtr(){
delete res_p;
cout << "the destructor of ResPtr\n";
}
friend class SharePtr<T>;
};
template<typename T>
class SharePtr {
public:
SharePtr(T *p, T i) : ptr(new ResPtr<T>(p)), val(i){
cout << "the constructor of SharePtr and the use count is " << ptr->use_num << endl;;
}
SharePtr(const SharePtr& rhs) : ptr(rhs.ptr), val(rhs.val) {
++ptr->use_num;
cout << "the copy constructor of SharePtr and the use of count is " << ptr->use_num << endl;
}
~SharePtr() {
cout << "the destructor of SharePtr and the use of count is " << ptr->use_num << endl;
if(--ptr->use_num == 0){
cout << "relese memory\n";
delete ptr;
}
}
T &operator*(){
return *this->ptr->res_p;
}
T *operator->(){
return this->ptr->res_p;
}
private:
ResPtr<T> *ptr; // point use_count
T val;
};
// test code
int main() {
{
SharePtr<int> hpa = SharePtr<int>{ new int (42), 100 };
{
// copy three objects
SharePtr<int> hpb{hpa};
SharePtr<int> hpc{hpb};
SharePtr<int> hpd{hpc};
};
cout << "inner end\n";
}
cout << "middle end\n";
return 0;
}
原文:https://www.cnblogs.com/MasterYan576356467/p/12178486.html