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

被折叠的 条评论
为什么被折叠?



