智能指针初探

先上代码 

#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由智能指针管理





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值