我试图基于Alexandrescu概念但使用c ++ 11习惯用法编写一个简单的ScopeGuard。namespace RAII{ template< typename Lambda > class ScopeGuard { mutable bool committed; Lambda rollbackLambda; public: ScopeGuard( const Lambda& _l) : committed(false) , rollbackLambda(_l) {} template< typename AdquireLambda > ScopeGuard( const AdquireLambda& _al , const Lambda& _l) : committed(false) , rollbackLambda(_l) { _al(); } ~ScopeGuard() { if (!committed) rollbackLambda(); } inline void commit() const { committed = true; } }; template< typename aLambda , typename rLambda> const ScopeGuard< rLambda >& makeScopeGuard( const aLambda& _a , const rLambda& _r) { return ScopeGuard< rLambda >( _a , _r ); } template<typename rLambda> const ScopeGuard< rLambda >& makeScopeGuard(const rLambda& _r) { return ScopeGuard< rLambda >(_r ); }}这是用法:void SomeFuncThatShouldBehaveAtomicallyInCaseOfExceptions() { std::vector<int> myVec; std::vector<int> someOtherVec; myVec.push_back(5); //first constructor, adquire happens elsewhere const auto& a = RAII::makeScopeGuard( [&]() { myVec.pop_back(); } ); //sintactically neater, since everything happens in a single line const auto& b = RAII::makeScopeGuard( [&]() { someOtherVec.push_back(42); } , [&]() { someOtherVec.pop_back(); } ); b.commit(); a.commit();}因为我的版本比大多数示例(例如Boost ScopeExit)短得多,所以我想知道我要保留哪些专业。希望我在80/20的情况下(其中80%的代码具有20%的代码行的整洁度),但我忍不住想知道我是否缺少一些重要的东西,或者是否有一些不足之处提到此版本的ScopeGuard习惯用法
3 回答
- 3 回答
- 0 关注
- 1000 浏览
添加回答
举报
0/150
提交
取消