• C++my_auto_ptr类


    my_auto_ptr通过它的析构函数来调用delete删除某对象的指针,来达到自动释放内存,而不需要显示的调用delete某对象。

    (1)实现自动释放

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    struct People 
    {
    public:
        People() {cout << "People" << endl;}
        ~People() {cout << "~People" << endl;}
        void run(void) const {cout << "Peple can run!" << endl;}
    };
    
    class my_auto_ptr
    {
    public:
        my_auto_ptr(People* p) : p(p) {}
        ~my_auto_ptr() {delete p;}
    private:
        People* p;
    };
    
    int main(int argc, char *argv[])
    {
        my_auto_ptr ptr(new People);
    
        return 0;
    }

    程序输出:

    People

    ~People

    (2)实现调用该对象的成员

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    struct People 
    {
    public:
        People() {cout << "People" << endl;}
        ~People() {cout << "~People" << endl;}
        void run(void) const {cout << "Peple can run!" << endl;}
    };
    
    class my_auto_ptr
    {
    public:
        my_auto_ptr(People* p) : p(p) {}
        ~my_auto_ptr() {delete p;}
        People* operator->() const {cout << "->" << endl; return p;}
        const People& operator*() const {cout << "*" << endl; return *p;}
        const People* operator&() const {cout << "&" << endl; return p;}
    private:
        People* p;
    };
    
    int main(int argc, char *argv[])
    {
        my_auto_ptr ptr(new People);
        
        ptr->run();
        (*ptr).run();
        &ptr;
    
        return 0;
    }
    
    /*
    总结:
    
    ptr->run();
    这里ptr是一个my_auto_ptr对象,p->run的含义与(p.operator->())->run求值相同。
    p.operator->()返回对People对象的指针,然后对返回的People调用run()函数。
    */

    程序输出:

     People
    ->
    Peple can run!
    *
    Peple can run!
    &
    ~People

    (3)实现泛型版本

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    struct People 
    {
    public:
        People() {cout << "People" << endl;}
        ~People() {cout << "~People" << endl;}
        void run(void) const {cout << "Peple can run!" << endl;}
    };
    
    class Student {};
    
    template<typename T>
    class my_auto_ptr
    {
    public:
        my_auto_ptr(T* p) : p(p) {}
        ~my_auto_ptr() {delete p;}
        T* operator->() const {cout << "->" << endl; return p;}
        const T& operator*() const {cout << "*" << endl; return *p;}
    private:
        T* p;
    };
    
    int main(int argc, char *argv[])
    {
        my_auto_ptr<People> ptr1(new People);
        my_auto_ptr<Student> ptr2(new Student);
    
        return 0;
    }
  • 相关阅读:
    MVC动态添加文本框,后台使用FormCollection接收
    使用结构struct作为Dictionary<TKey,TValue>的键
    扩展方法的几个实例,扩展基本类型、接口、通过反射让扩展方法使用私有成员等
    使用Enum.TryParse()实现枚举的安全转换
    .NET泛型04,使用Lazy<T>实现延迟加载
    .NET泛型03,泛型类型的转换,协变和逆变
    .NET泛型02,泛型的使用
    dd、split、csplit命令
    seq命令
    uniq命令
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3063103.html
Copyright © 2020-2023  润新知