模板强化RAII

 RAII的应用在C++这种高危语言中尤其重要,结合模板,效果更爽。

先看应用:
#include "stdafx.h"

using namespace Loki;

void myFree(char* s)
{
 if (s != NULL)
 {
  free(s);
 }
 printf("myFree(char*) was invoked.\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
 {
  char* s = (char*)malloc(128);
  ScopeGuard sg = MakeGuard(myFree, s);
  //sg.Dismiss();
 }
 
 system("pause");
 return 0;
}

再看模板原理:
namespace Loki
{
 class ScopeGuardImplBase
 {
  ScopeGuardImplBase& operator =(const ScopeGuardImplBase&);

 protected:

  ~ScopeGuardImplBase()
  {}

  ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
   : dismissed_(other.dismissed_)
  {
   other.Dismiss();
  }

  template <typename J>
  static void SafeExecute(J& j) throw()
  {
   if (!j.dismissed_)
   try
   {
    j.Execute();
   }
   catch(...)
   {}
  }

  mutable bool dismissed_;

 public:
  ScopeGuardImplBase() throw() : dismissed_(false)
  {}

  void Dismiss() const throw()
  {
   dismissed_ = true;
  }
 };

 typedef const ScopeGuardImplBase& ScopeGuard;

 template <typename F, typename P1>
 class ScopeGuardImpl1 : public ScopeGuardImplBase
 {
 public:
  static ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
  {
   return ScopeGuardImpl1<F, P1>(fun, p1);
  }

  ~ScopeGuardImpl1() throw()
  {
   SafeExecute(*this);
  }

  void Execute()
  {
   fun_(p1_);
  }

 protected:
  ScopeGuardImpl1(F fun, P1 p1) : fun_(fun), p1_(p1)
  {}

  F fun_;
  const P1 p1_;
 };

 template <typename F, typename P1>
 inline ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1)
 {
  return ScopeGuardImpl1<F, P1>::MakeGuard(fun, p1);
 }
} // namespace Loki

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值