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;
}

猜你喜欢

转载自www.cnblogs.com/aelite/p/11312755.html