C++智能指针实现
手动实现一个智能指针,留着以后用得到的时候再看
#include <iostream>
using namespace std;
template <class T>
class smart_ptr {
public:
smart_ptr (T* ptr = nullptr) : _ptr(ptr), _pCount(nullptr) {
if (_ptr) {
_pCount = new int (1);
}
cout << "smart_ptr (T* ptr)" << endl;
}
smart_ptr (const smart_ptr<T>& sp) : _ptr(sp._ptr), _pCount(sp._pCount){
if (_ptr)
(*_pCount)++;
cout << "smart_ptr (smart_ptr<T>& ptr)" << endl;
}
~smart_ptr () {
if (_ptr && --(*_pCount) == 0) {
delete _ptr; delete _pCount;
_ptr = nullptr; _pCount = nullptr;
}
cout << "~smart_ptr ()" << endl;
}
smart_ptr<T>& operator= (const smart_ptr<T>& ptr) {
cout << "smart_ptr<T> operator= (const smart_ptr<T>& ptr)" << endl;
if (_ptr == ptr._ptr)
return *this;
if (_ptr && --(*_pCount) == 0) {
delete _ptr; delete _pCount;
_ptr = nullptr; _pCount = nullptr;
}
_ptr = ptr._ptr;
_pCount = ptr._pCount;
if (_ptr)
++(*_pCount);
return *this;
}
int useCount () {
return *_pCount;
}
T& operator* () {
return *_ptr;
}
T* operator-> () {
return _ptr;
}
T* get () {
return _ptr;
}
private:
T* _ptr;
int* _pCount;
};
class A {
public:
int i;
A (int n) : i(n) {}
~A () {cout << i << " destructed" << endl;}
};
int main (){
smart_ptr<A> sp1(new A(2));
smart_ptr<A> sp2(sp1);
smart_ptr<A> sp3;
sp3 = sp2;
cout << sp1->i << "," << sp2->i << "," << sp3->i << endl;
A* p = sp3.get();
cout << p->i << endl;
sp1 = new A(3);
sp2 = new A(4);
cout << sp1->i << endl;
sp3 = new A(5);
cout << "end" << endl;
cout << (*sp3).i << " " << sp3->i << endl;
return 0;
}
还没有评论,来说两句吧...