智能指针的自定义及重载->

智能指针:
(1)智能指针能够自动的释放内存,就不必自己手动的delete释放内存空间
(2)智能指针实际上是一个模板类,它的数据内型为auto_ptr<…>,定义方式例如:auto_ptr ptr(new int);不能是auto_ptr ptr=new int;

代码:


#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)
    {
        this->ptr = ptr;//ptr = new A(10)
    }

    ~MyAutoPtr() {   //析构函数实现释放内存空间
        if (this->ptr != NULL) {
            cout << "delte ptr" << endl;
            delete ptr;
            this->ptr = NULL;
        }
    }

    A* operator->()//当自定义智能指针时,->需要被重载
    {
        return this->ptr;
    }

    //返回A的引用来访问*ptr
    A& operator*()
    {
        return *ptr;
    }

private:
    A *ptr;//注意自定义智能指针时,不能是void *ptr
};
//测试C++自身的智能指针
void test1()
{
#if 0
    A* ap = new A(10);

    ap->func();
    (*ap).func();

    delete ap;
    auto_ptr<int> ptr(new int);
#endif
    auto_ptr<A> ptr(new A(10));

    ptr->func();
    (*ptr).func();
}


void test2()
{
    MyAutoPtr my_p(new A(10));

    my_p->func(); //my_p.ptr -> func()
    (*my_p).func(); //  *ptr.func()
}
int main(void)
{

    //test1();
    test2();

    return 0;
}

猜你喜欢

转载自blog.csdn.net/yjh_SE007/article/details/78427279