zoukankan      html  css  js  c++  java
  • RAII Theory && auto_ptr

    RAII(Resource Acquisition is Initialization),也称为"资源获取即初始化",是C++语言的一种管理资源,避免泄露的惯用法。

    C++标准保证任何情况下,已构造的对象最终会销毁,即它的析构函数最终会被调用。简单的说,RAII的做法是使用一个对象,在其构造时获取资源,在对象生命期控制对资源的访问使之始终保持有效,最后在对象析构的时候释放资源。

    #include <iostream>
    #include <memory>
    using namespace std;
    
    class A
    {
    public:
       A()
       {
          cout << "A()" << endl;
       }
       void xxxx()
       {
          cout << "xxxx" << endl;
       }
       ~A()
       {
          cout << "~A" << endl;
       }
    };
    
    void foo()
    {
       // A *p = new A;
       // delete p;
       auto_ptr<A> p(new A);
       p->xxxx();
       (*p).xxxx();
    }
    int main()
    {
       foo();
       return 0;
    }
    #include <iostream>
    #include <memory>
    using namespace std;
    
    class A
    {
    public:
       A()
       {
          cout << "A()" << endl;
       }
       void xxxx()
       {
          cout << "xxxx" << endl;
       }
       ~A()
       {
          cout << "~A" << endl;
       }
    };
    
    class SmartPtr
    {
       public:
       SmartPtr(A* pa)
       {
          _pa = pa;
       }
       A& getAref()
       {
          return *_pa;
       }
       A& operator*()
       {
          return *_pa;
       }
       A* getAp()
       {
          return _pa;
       }
       A* operator->()
       {
          return _pa;
       }
       ~SmartPtr()
       {
          delete _pa;
       }
       private:
       A* _pa;
    };
    
    void foo()
    {
       SmartPtr sp (new A);
       // sp.getAref().xxxx();
       // sp.getAp()->xxxx();
       (*sp).xxxx();
       sp->xxxx();
    }
    int main()
    {
       foo();
       return 0;
    }
  • 相关阅读:
    开源控件PullToRefreshGridView的使用(三)
    JS中的运算符 以及变量和输入输出
    HTML中表格
    JS中 事件冒泡与事件捕获
    JS中的循环结构
    UML类图详解
    一步一步生成图片水印
    快速生成缩略图
    ==和Equal()的区别
    屌丝程序人生(下)
  • 原文地址:https://www.cnblogs.com/aelite/p/11312755.html
Copyright © 2011-2022 走看看