#include<iostream>
using namespace std;
template<class T> class smartPoiter;
template<class T>
class u_ptr
{
private:
int num;
T *ptr;
u_ptr(T* p): num(1),ptr(p) {cout << "创建" << endl;}
~u_ptr()
{
delete ptr;
}
friend class smartPoiter<T>;
};
template<class T>
class smartPoiter
{
private:
u_ptr<T>* poiter;
public:
smartPoiter(T* p = 0):poiter(new u_ptr<T>(p)) {}
smartPoiter(smartPoiter& rhs): poiter(rhs.poiter)
{
++(poiter->num);
cout << "拷贝构造 还有" << poiter->num << endl;
}
smartPoiter& operator=(const smartPoiter& rhs);
T* operator->() const //const表明不能修改主调对象
{
return(poiter->ptr);
}
T& operator*() const
{
return(*(poiter->ptr));
}
~smartPoiter()
{
if(--(poiter->num) == 0)
{
delete poiter;
cout << "全部删除" << endl;
}
else
{
cout << "还有" << poiter->num << "个智能指针" << endl;
}
}
};
//rhs的应用次数加1,主调对象减1
template<class T>
smartPoiter<T>&
smartPoiter<T>::operator=(const smartPoiter<T>& rhs)
{
++(rhs.poiter->num); //这种写法还是可以
if(--(poiter->num) == 0)
{
delete poiter;
}
poiter = rhs.poiter;
return(*this);
}
struct point
{
int x,y;
point(int a,int b): x(a),y(b) {}
};
int main()
{
smartPoiter<point> p(new point(5,6));
cout << p->x << " " << p->y << endl;
smartPoiter<point> p1 = p;
cout << p1->x << " " << p1->y << endl;
// p = p; //测试自我复制
cout << p->x << " " << p->y << endl;
cout << (*p).x << " " << (*p).y << endl;
return(0);
}
智能指针(引用计数版)
最新推荐文章于 2024-04-10 13:07:20 发布