C++之资源转移智能指针auto_ptr的实现

目录

概念:

使用标准库auto_ptr指针:

自定义智能指针的底层实现:


概念:

        auto_ptr智能指针已在C++17中移除。可用作学习智能指针的入门。

        auto_ptr又称资源转移指针,即发生拷贝构造或=号赋值后,原auto_ptr指针为空。

使用标准库auto_ptr指针:

        头文件:#include <memory>

        自定义一个Stu类:

#include <iostream>
#include <memory>
using namespace std;

class Stu
{
private:
    string name;
    int age;
public:

    Stu(string name, int age)
    {
        this->name = name;
        this->age = age;
        cout << "Stu的构造" << endl;
    }

    ~Stu()
    {
        cout << "Stu的析构" << endl;
    }

    void showInfo()
    {
        cout << "姓名:" << this->name << " 年龄:" << this ->age << endl;
    }
};

        标准库auto_ptr指针:

int main()
{
    //使用系统auto_ptr智能指针
    auto_ptr<Stu> ptr1(new Stu("zhangsan", 20));
    auto_ptr<Stu> ptr2 = ptr1;
    cout << "-------------- " << endl;


    //原因是,auto_ptr发生权限转移,会将自身的资源释放,ptr1就无内容了
    ptr2->showInfo(); //姓名:zhangsan 年龄:20
// ptr1->showInfo(); //姓名: (为空,且不往下执行了)

}

        运行结果:

        

自定义智能指针的底层实现:

        仍用上边的Stu类。

        自定义智能指针类:

//自己实现atuo_ptr类
template <class T>
class AUTO_ptr
{
private:
    T * ptr;

public:
    //构造函数,将初始化传的指针赋值给本类指针,如果空传参,则给指针默认赋空指针
    AUTO_ptr(T* ptr = nullptr)
    {
        this->ptr = ptr;
    }

    ~AUTO_ptr()
    {
        delete ptr;
    }

    //拷贝构造
    AUTO_ptr(const AUTO_ptr& other)
    {
        this->ptr = other.ptr;
        const_cast<AUTO_ptr&> (other).ptr = nullptr;
    }

    //=号重载
    AUTO_ptr& operator = (const AUTO_ptr& other)
    {
        if(this == &other)

        {
            return *this;
        }

        if(this->ptr != nullptr)
        {
            delete ptr;
            this->ptr = other.ptr;
            const_cast<AUTO_ptr&> (other).ptr = nullptr;
        }
        return *this;
    }

    T& operator* ()
    {
        return *ptr;
    }

    T* operator-> ()
    {
        return ptr;
    }

    T* get()
    {
        return ptr;
    }
};

        主函数:

int main()
{

//用自己定义的auto_ptr类
    AUTO_ptr<Stu> ptr3(new Stu("lisi", 22));
    AUTO_ptr<Stu> ptr4 = ptr3;
    cout << "-----------------" << endl;


    ptr4->showInfo(); //姓名:lisi 年龄:22
// ptr3->showInfo(); //姓名: (为空,且不往下执行了)
    cout << "----------" << endl;


    ptr4.get()->showInfo(); //姓名:lisi 年龄:2
    (*ptr4).showInfo(); //姓名:lisi 年龄:22

}

        运行结果:

        

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值