問題:
如何使用基於Alexcucu簡單ScopeGuard?
回答:
以下是基於C 11 慣用法的ScopeGuard 實現:
<code class="cpp">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 ); } }</code>
用法:
<code class="cpp">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(); }</code>
優點:
潛在問題:
以上是以下是幾個符合文章內容的英文標題: 簡潔的標題(簡短且直接): * How to Build a Simple ScopeGuard with C 11 Idioms? * Implementing a Simple ScopeGuard in C 11: A Practical Approach * C 11 ScopeGuard: A Concise and Practical I的詳細內容。更多資訊請關注PHP中文網其他相關文章!