先上代码
#include<iostream>
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 y; }
void setX(int xVal) { x = xVal; }
void setY(int yVal) { y = yVal; }
private:
int x, y;
};
class Ptr //记录具体的对象 和 次数
{
//private:
public:
friend class smart_ptr;
Ptr(point *ptr) :p(ptr), count(1) { }
~Ptr() { delete p; }
int count;
point *p;
};
class smart_ptr
{
public:
smart_ptr(point *ptr) :rp(new Ptr(ptr)) { cout<<"默认构造"<<endl;}
smart_ptr(const smart_ptr &sp) :rp(sp.rp) { ++rp->count; cout<<"拷贝构造,"<<rp->count<<endl;}
smart_ptr& operator=(const smart_ptr& rhs) {
++rhs.rp->count;
std::cout<<"赋值构造"<<rhs.rp->count<<std::endl;
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:
public:
Ptr *rp;
};
int main()
{
point *pa = new point(1, 2);
{
smart_ptr sptr1(pa);
{
smart_ptr sptr2(sptr1); //显示的拷贝构造
{
smart_ptr sptr3=sptr1; //隐式的拷贝构造
}
}
}
cout << pa->getX ()<< endl;
//delete
return 0;
}
/*
int main()
{
point* pa = new point(1, 2);
smart_ptr sptr1(pa); //默认构造
{
smart_ptr sptr3(new point(3, 4)); //默认构造 最高效
smart_ptr sptr2(sptr1);
{
sptr2 = sptr3;
cout<<sptr1.rp->count<<endl;
}
}
cout << pa->getX ()<< endl;
return 0;
}
*/
目前还不是很了解private和public 所以改为public 方便打印
理解重点:多个指针sptr1/2/3对原变量pa的引用 以及拷贝构造、赋值构造(尤其是赋值构造) 画个图稍微更清晰一些
重点还是拷贝构造 赋值构造
只有在这两种情况下 引用才会++
所以 记录次数的count由智能指针管理