参考:https://blog.csdn.net/weixin_44056971/article/details/118637756
#include <bits/stdc++.h>
using namespace std;
template <typename T> class mySharedPointer {
public:
mySharedPointer(T *p) : count(new int(1)), _ptr(p) {
cout << "call sharedPointer constructor..." << endl;
}
mySharedPointer(mySharedPointer<T> &other)
: count(&(++*other.count)), _ptr(other._ptr) {
cout << "call sharedPointer copy constructor..." << endl;
}
T *operator->() { return _ptr; }
T &operator*() { return *_ptr; }
mySharedPointer<T> &operator=(mySharedPointer<T> &other) {
cout << "call sharedPointer assignment operator..." << endl;
++*other.count;
if (this->_ptr && 0 == --*this->count) {
delete _ptr;
delete count;
}
this->_ptr = other._ptr;
this->count = other.count;
return *this;
}
~mySharedPointer() {
if (--*count == 0) {
delete _ptr;
delete count;
cout << "call sharedPointer destructor..." << endl;
}
}
int getRef() { return *count; }
private:
int *count;
T *_ptr;
};
class Person {
public:
Person(int v) : value(v) { cout << "constructor " << value << "..." << endl; }
~Person() { cout << "desctructor" << value << "..." << endl; }
private:
int value;
};
int main() {
mySharedPointer<Person> p1(new Person(1));
mySharedPointer<Person> p2(new Person(2));
mySharedPointer<Person> p3 = p1;
p3 = p2;
cout << "Ref: " << p1.getRef() << " " << p2.getRef() << " " << p3.getRef()
<< endl;
return 0;
}
constructor 1...
call sharedPointer constructor...
constructor 2...
call sharedPointer constructor...
call sharedPointer copy constructor...
call sharedPointer assignment operator...
Ref: 1 2 2
desctructor2...
call sharedPointer destructor...
desctructor1...
call sharedPointer destructor...