自定义智能指针

#include<iostream>
#include<memory>//智能指针在其中
using namespace std;

class A
{
public:
    A(int a)
    {
        cout << "A()..." << endl;
        this->a = a;
    }

    void func()
    {
        cout << "a = " << this->a << endl;
    }
    ~A() {
        cout << "~A()..." << endl;
    }
private:
    int a;
};

//将智能指针的类写出来
class MyAutoPtr
{
public:

    MyAutoPtr(A *ptr)//这里不能用void * ,即万能指针。
                    //要指明数据类型,才能触发析构。
    {
        this->ptr = ptr;
    }
    ~MyAutoPtr() {
        if (this->ptr !=NULL)
        {
            cout << "delete ptr" << endl;
            delete ptr;
            this->ptr = NULL;
        }
    }
    //为了实现my_p.ptr->func();,即返回指针ptr
    A* operator->()
    {
        return this->ptr;
    }
    //为了实现(*ptr).func();,即返回对象
    A & operator*()
    {
        return *ptr;
    }

private:
    A *ptr;
};

//常规写法
void test1()
{
    A *ap = new A(10);
    ap->func();
    (*ap).func();//也可以这样调用

    delete ap;
}
//使用智能指针
void test2()
{
    auto_ptr<A> ptr(new A(10));//将a=10传入构造函数
    ptr->func();
    (*ptr).func();
    //不用delete,会自动触发析构函数,自动回收,类似java的new对象
}
//自定义智能指针
void test3()
{
    MyAutoPtr my_p(new A(10));//将a=10传入构造函数
    my_p->func();//使用->操作符重载,为了使my_ptr对象,产生指针的效果
                    //my_p.ptr->func(); 注意my_p是个对象
    (*my_p).func();//使用*操作符重载,为了使my_ptr对象,产生指针的效果
                    //*ptr.func();
}

int main()
{
    int *p = new int;
    //*p = 20;
    //delete p;//需要手动删除开辟空间,而java等其他语言不需要

    //智能指针是个类auto_ptr,调用构造函数ptr(new int),数据类型auto_ptr<int>
    auto_ptr<int>  ptr(new int);//智能指针,不需要手动delete,会自动回收
    *ptr = 20;

    test1();
    cout << "-----------------------" << endl;
    test2();
    cout << "-----------------------" << endl;
    test3();
    return 0;
}

结果:

这里写图片描述

总结:

#include//智能指针头文件

智能指针是个类auto_ptr,调用构造函数ptr(new int),数据类型auto_ptr
auto_ptr ptr(new int);//智能指针,不需要手动delete,会自动触发析构函数,自动回收,类似java的new对象

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值