#include <iostream>
#include <assert.h>
using namespace std;
class A {
public:
A(int a, int b) {
x = a;
y = b;
};
int x;
int y;
void test() {
cout << "hello test!" << endl;
};
};
template<typename T>
class smartPtr {
public:
smartPtr() {
cout << "default construct" << endl;
_ptr = nullptr;
_cont = nullptr;
};
smartPtr(T * ptr) {
cout << "normal construct" << endl;
_ptr = ptr;
_cont = new int();
(*_cont) = 1;
};
smartPtr(const smartPtr& sp) {
cout << "copy construct" << endl;
_ptr = sp._ptr;
_cont = sp._cont;
(*_cont)++;
};
smartPtr & operator=(const smartPtr& sp) {
cout << "operator =" << endl;
if(this->_ptr != sp._ptr) { // 防止自赋值
if(_ptr != nullptr) {
(*_cont)--;
if((*_cont) == 1) {
delete _ptr;
_ptr = nullptr;
delete _cont;
_cont = nullptr;
}
}
_ptr = sp._ptr;
_cont = sp._cont;
(*_cont)++;
}
return *this;
}
~smartPtr() {
cout << "destructor" <<endl;
if(_ptr != nullptr) { // 指针非空时
if((*_cont) == 1) { // 引用计数将减为 0
cout << "delete object" << endl;
delete _ptr;
_ptr = nullptr;
delete _cont;
_cont = nullptr;
} else {
(*_cont)--; // 引用计数减小
}
}
};
T & operator*() {
assert(_ptr != nullptr);
return *_ptr;
}
T * operator->() {
assert(_ptr != nullptr);
return _ptr;
}
int getCount() {
if(_cont != nullptr)
return *_cont;
return -1;
}
private:
T * _ptr;
int * _cont;
};
int main()
{
double * a = new double(10.2);
int * b = new int(3);
A * c = new A(1,2);
smartPtr<double>s(a);
smartPtr<int> s2(b);
smartPtr<int> s3 = s2;
smartPtr<A> s4(c);
smartPtr<A> s5 = s4;
s2 = s3;
cout << *s << endl;
cout << s.getCount() << endl;
cout << *s2 << endl;
cout << s.getCount() << endl;
cout << s2.getCount() << endl;
cout << *s3 << endl;
cout << s.getCount() << endl;
cout << s4->x << " " << s4->y << endl;
s4->test();
cout << s5->x << " " << s5->y << endl;
cout << s5.getCount() << endl;
return 0;
}
智能指针的简单实现
最新推荐文章于 2022-05-20 18:27:06 发布