C++智能指针简单实现

#include <stdio.h>
#include <stdlib.h>
class Temp
{
public:
    Temp() {
        printf("%s:构造函数\n", __FUNCTION__);
    }
    ~Temp()
    {
        printf("%s:析构函数\n", __FUNCTION__);
    }
    void func() 
    {
        printf("%s\n", __FUNCTION__);
    }
private:

};

template <class T>
class SmartPointer
{
public:
    SmartPointer(){}
    SmartPointer(T* data)
    {
        p = data;
    }
    ~SmartPointer() {
        delete p;
    }
    //重载->运算符
    T* operator->()
    {
        return p;
    }
    T& operator*()
    {
        return *p;
    }
private:
    T* p;
};

 

int main(int argc, char* argv[])
{
    SmartPointer<Temp> sp(new Temp);
    //sp.operator->()->func();
    sp->func();
    (*sp).func();

    getchar();
    return 0;
}

 

posted @ 2023-02-27 10:24  一夜梦想  阅读(8)  评论(0编辑  收藏  举报