泛化的ScopeGuard模板类

本文介绍了一种资源管理技术ScopeGuard的设计与实现细节,通过模板元编程的方式确保资源的正确释放。提供了两种ScopeGuard的使用方式,一种针对成员函数,另一种针对全局函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#pragma once

#include 
<cassert>
#include 
<memory>
#include 
"non_copy_able.h"



class ScopeGuardImp : private NonCopyable
{
public:
        ScopeGuardImp() 
{ };
        
virtual ~ScopeGuardImp(){ }
}
;



template
<class Type, class Fore, class Aft>                    
class ScopeGuardMF : public ScopeGuardImp

private:
        typedef typename 
void (Type::*MFun)(void);
private:
        Type    
*m_type;
        Fore    m_fore;
        Aft        m_aft;
public:
        ScopeGuardMF(Type 
*ptype, Fore fore, Aft aft)
        
{
                assert(ptype 
!= NULL);
                m_type 
= ptype;
                m_fore 
= fore;
                m_aft 
= aft;
                (m_type
->*m_fore)();
        }


        
~ScopeGuardMF()
        
{
                (m_type
->*m_aft)();
        }

}
;


template
<class Fore, class Aft>
class ScopeGuardFun : public ScopeGuardImp

private:
        Fore    m_fore;
        Aft        m_aft;
public:
        ScopeGuardFun(Fore fore, Aft aft)
        
{
                m_fore 
= fore;
                m_aft 
= aft;
                m_fore();
        }

        
        
~ScopeGuardFun()
        
{
                m_aft();
        }


}
;


class ScopeGuard  : private NonCopyable
{
private:
        std::auto_ptr
<ScopeGuardImp>   m_pimp;
public:
        template
<typename Type, typename Fore, typename Aft>
        ScopeGuard(Type 
*ptype, Fore fore, Aft aft)
        
{
                m_pimp.reset(
new ScopeGuardMF<Type, Fore, Aft>(ptype, fore, aft));
        }

        
        template
<typename Fore, typename Aft>
        ScopeGuard(Fore fore, Aft aft)
        
{
                m_pimp.reset(
new ScopeGuardFun<Fore, Aft>(fore, aft));
        }


        
~ScopeGuard() { }

}
;



 

测试代码:

 



class Test
{
public:
        
int fore() { printf("fore ");  return 8;}
        
void after() { printf("after "); }
}
;

void fore() { printf("aaaaa "); }
double after() { printf("bbbbb "); return 33.6;}

int main()
{
        
{
                Test test;
                ScopeGuard guard1(
&test, &Test::fore, &Test::after);
        }

        
{
                ScopeGuard guard2(fore, after);
        }

        
        
        cin.
get();

        
return 0;
}
;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值