Add

ScopeGuard 取代 std::auto_ptr 实现异常安全


转至:http://www.cppblog.com/eXile

为了实现异常安全,经常见到下列代码,而且这也是被标准推荐的方式: 

void  f()
{ 
  std::auto_ptr<SomeType>  ptr(new SomeType);  

  //…and other operation

 }

boost替代scoped_ptr 来强化这个概念。这种方案的缺陷是只能用于删除指针,它实际上表达的是以下概念:

void f()
{ 
  SomeType * ptr = new SomeType; 
         ON_BLOCK_EXIT(delete ptr);

  //…and other operation

 }

如何在退出作用域时自动执行所指定的函数,实现更广泛意义上的异常安全,而不是scoped_ptr, scoped_array,  scoped_function 等一系列替代品。LOKI的那个变态大师又提出了一种更好的办法,类似于下列代码:

template < T> inline void Delete(T* p)
{  delete p; }

void f()
{ 
  SomeType * ptr = new SomeType; 
         ON_BLOCK_EXIT(&Delete,   ptr);

  //…and other operation
 }

实现 ON_BLOCK_EXIT 的自动调用,关键是实现一个高效的 ScopeGuard,LOKI中实现大致如下:
  
 class ScopeGuardImplBase
{
public:
    void Dismiss() const throw()
    {    dismissed_ = true;    }
protected:
    ScopeGuardImplBase() : dismissed_(false)
    {}
    ScopeGuardImplBase(const ScopeGuardImplBase& other)
    : dismissed_(other.dismissed_)
    {    other.Dismiss();    }
    ~ScopeGuardImplBase() {} // nonvirtual (see below why)
    mutable bool dismissed_;

private:
    // Disable assignment
    ScopeGuardImplBase& operator=(
        const ScopeGuardImplBase&);
};

										template <typename Fun, typename Parm>class ScopeGuardImpl1 : public ScopeGuardImplBase{public:    ScopeGuardImpl1(const Fun& fun, const Parm& parm)    : fun_(fun), parm_(parm)     {}    ~ScopeGuardImpl1()    {        if (!dismissed_) fun_(parm_);    }private:    Fun fun_;    const Parm parm_;};		
										template <typename Fun, typename Parm>ScopeGuardImpl1<Fun, Parm>MakeGuard(const Fun& fun, const Parm& parm){    return ScopeGuardImpl1<Fun, Parm>(fun, parm);}		

typedef const ScopeGuardImplBase& ScopeGuard; 

#define ON_BLOCK_EXIT      ScopeGuard g = MakeGuard

这只是实现了一个参数的情况,并作了简化处理,更具体的实现,请参看Loki库。

Random Posts Recent Comments

  • 女友糖尿病害我蛀牙 Says:

    汗一个…...

  • Htj06 Says:

    zhenyouchuangyi...

  • 电商圈 Says:

    试图该怎么建立啊,,怎在程序中是吸纳...

  • edward Says:

    看得人心旷神怡,好文,情不自禁的顶一下...

  • Daniel Says:

    我也在处理这个问题,没有找到好的方法。我用了楼上兄弟的方法,还是可以的。不知道您找到好的方法了吗、我暂时楼上兄弟的方法。...

  • 卡,卡 Says:

    弱弱问一句:博主,你博客的模板这样设计pv高吗?...

  • 站长工具 Says:

    博主,兔年快乐!...

  • health Says:

    great post!!I hope I can read more in your website....

  • pdu Says:

    好博文,支持分享...

  • 站长工具 Says:

    博主的文章很不错,我是站长工具-站长精灵的作者,一款专业的SEO工具软件(可以帮您提高博客的流量),想跟您交换个链接,不知可否...

Tag Cloud

arm audio blog brew cache class debug flash google html j2me java javascript Joke linux lua mobile mtk php python ror ruby server shell stream unix web windows 优化 动态加载 女人 女生 平台 开发 手机 技术 流媒体 测试 漫画 生活 男人 男生 缓存 芯片