#include<iostream>
#include<string>
using namespace std;
class Point{
public:
Point(int xVal = 0,int yVal = 0) : x(xVal), y(yVal) {}
int getX() const {return x;}
int getY() const {return x;}
void setX(int xVal) {x = xVal;}
void setY(int yVal) {y = yVal;}
private:
int x,y;
};
class U_ptr{
private:
friend class Smart_ptr;
U_ptr(Point* dummy):p(dummy),count(1){}
~U_ptr(){
delete p;
}
int count;
Point* p;
};
class Smart_ptr{
public:
Smart_ptr(Point* ptr):rp(new U_ptr(ptr)){}
Smart_ptr(Smart_ptr* ptr):rp(ptr.rp){
rp->count ++ ;
}
Smart_ptr& operator=(Smart_ptr* rhs){
rhs.rp->count++;
if(--rp->count==0){
delete rp;
}
rp = rhs.rp;
return *this;
}
~Smart_ptr(){
if(--rp->count==0)
delete rp;
else
cout<<"还有 "<<rp->count<<endl;
}
private:
U_ptr* rp;
};
int main(){
Point* p = new Point(4,3);
{
Smart_ptr sptr1(p);
{
Smart_ptr sptr2(sptr1);
{
Smart_ptr sptr2 = sptr1;
}
}
}
return 0;
}
网友评论