我試圖基于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 回答
- 0 關注
- 1026 瀏覽
添加回答
舉報
0/150
提交
取消