C++中的解引用与智能指针

本文介绍了C++中的智能指针,包括其在资源管理中的作用,常规情况下的使用,以及C++98的`auto_ptr`,C++11/14标准中的`unique_ptr`、`shared_ptr`和`weak_ptr`。还提到了Boost库中的多种智能指针类型,并简单提及了自定义智能指针的概念。

一、概述

在C语言和C++中,不管我们用C语言的库函数malloc开辟了一块内存,还是用C++的操作符new出了一块内存,我们都要同过free和delete去释放内存。而对于其他高级语言来说,当我们开辟一块内存用完之后,我不用去管这块内存的释放,操作系统默认会帮我们把这块内存释放了。其实这样的机制在C++中也有,只是很少被用到而已,它就是所谓的智能指针。

二、智能指针

1、常规情况
void foo()
{
    A* p = new A;
    delete p;
}
2、智能指针
#include <iostream>
#include <memory>
using namespace std;

class A
{
    public:
        A()
        {
            cout << "this is constructor" << endl;  
        }

        ~A()
        {
            cout << "this is destructor" << endl;   
        }

        void dis()
        {
            cout << "class A`s dis()" << endl;
        }
};

int main()
{
    //使用智能指针
    auto_ptr auto_ptr<A>p(new A);
    p->dis();
    return 0;   
}

这里有必要说明一下,智能指针auto_ptr属于C++98标准的,它能部分第解决资源释放问题。上面这个例子就是说明”自动指针”能够释放资源的案例。auto_ptr 构造函数接受new操作符或者工厂创建出的对象指针作为参数,从而代理了原始指针。虽然它是一个对象,但因为重载了operator*operator->,其行为类似指针,可以把它用在大多数普通指针可用的地方。当退出作用域时(离开函数main或者发生异常),C++语言会保证auto_ptr对象销毁,调用auto_ptr的析构函数,进而使用delete操作符删除原始指针释放资源。
由于auto_ptr存在一些局限性,故而在C++11/14标准中提供了unique_ptrshare_ptrweak_ptr 。除此之外,boost也提供智能指针,在boost.smart_ptr库中,boost提供了六种智能指针,分别是scoped_ptr , scoped_arrayshared_ptrshare_arrayweak_ptr , intrusive_ptr 。它们是轻量级对象,速度与原始指针相差无几,都是异常安全的(exeception safe),而且对于所有指向的类型T也仅有一个很小的要求:类型T的析构函数不能抛出异常。

3、自定义智能指针
#include <iostream>
#include <memory>
using namespace std;

class A
{
    public:
        A()
        {
            cout << "this is constructor" << endl;  
        }

        ~A()
        {
            cout << "this is destructor" << endl;   
        }

        void dis()
        {
            cout << "class A`s dis()" << endl;
        }
};

class self_PMA
{
    public:
        self_PMA(A *p):_p(p){}

        ~self_PMA()
        {
            delete p;
        }

        A& operator*()
        {
            return *_p;
        }
        A* operator->()
        {
            return _p;
        }
    private:
        A* _p;
};

int main()
{
    //使用智能指针
    self_PMA self_PMA<A>p(new A);
    p->dis();
    return 0;   
}

自定义智能指针重载了operator *operator->

类名& operator*()
{
    函数体
}

类名* operator-­‐>()
{
    函数体
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

The_Web3_社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值