最簡單、最簡潔的C 11 ScopeGuard
在C 11 中,有一個簡單的習慣用法可以實現ScopeGuard,從而簡化ScopeGuard,從而簡化錯誤和資源處理。以下是一個簡單的解釋和實現:
概念:
ScopeGuard 是一個C 類,它提供了一種定義程式碼區塊的方法,當創建守衛的範圍退出。這樣可以輕鬆進行清理和錯誤處理,確保即使在特殊情況下也能釋放資源或採取操作。
實作:
<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>
在此範例中,Scope確保即使在函數範圍內引發異常,也會執行清理操作(從向量中彈出元素)。
簡單性和局限性:
ScopeGuard 習慣用法的這種實現相對簡單和簡潔,使其易於使用和理解。然而,原問題的作者也對潛在的缺陷或缺失的專業提出了擔憂。讓我們解決這些問題:
為了解決這些問題,以下是 ScopeGuard 實作和用法的更新版本:
<code class="cpp">namespace RAII { template< typename Lambda > class ScopeGuard { bool committed; Lambda rollbackLambda; public: ScopeGuard( const Lambda& _l) : committed(false) , rollbackLambda(_l) {} ScopeGuard( const ScopeGuard& _sc) : committed(false) , rollbackLambda(_sc.rollbackLambda) { if (_sc.committed) committed = true; else _sc.commit(); } ScopeGuard( ScopeGuard&& _sc) : committed(false) , rollbackLambda(_sc.rollbackLambda) { if (_sc.committed) committed = true; else _sc.commit(); } //WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope guard never finished initialistion.. template< typename AdquireLambda > ScopeGuard( const AdquireLambda& _al , const Lambda& _l) : committed(false) , rollbackLambda(_l) { std::forward<AdquireLambda>(_al)(); } //WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope guard never finished initialistion.. template< typename AdquireLambda, typename L > ScopeGuard( AdquireLambda&& _al , L&& _l) : committed(false) , rollbackLambda(std::forward<L>(_l)) { std::forward<AdquireLambda>(_al)(); // just in case the functor has &&-qualified operator() } ~ScopeGuard() { if (!committed) rollbackLambda(); } inline void commit() { committed = true; } }; //WARNING: only safe if adquire lambda does not throw, otherwise release lambda is never invoked, because the scope guard never finished initialistion.. template< typename aLambda , typename rLambda> ScopeGuard< rLambda > // return by value is the preferred C++11 way. makeScopeGuardThatDoesNOTRollbackIfAdquireThrows( aLambda&& _a , rLambda&& _r) // again perfect forwarding { return ScopeGuard< rLambda >( std::forward<aLambda>(_a) , std::forward<rLambda>(_r )); // *** no longer UB, because we're returning by value } template< typename aLambda , typename rLambda> ScopeGuard< rLambda > // return by value is the preferred C++11 way. makeScopeGuardThatDoesRollbackIfAdquireThrows( aLambda&& _a , rLambda&& _r) // again perfect forwarding { auto scope = ScopeGuard< rLambda >(std::forward<rLambda>(_r )); // *** no longer UB, because we're returning by value _a(); return scope; } template<typename rLambda> ScopeGuard< rLambda > makeScopeGuard(rLambda&& _r) { return ScopeGuard< rLambda >( std::forward<rLambda>(_r )); } namespace basic_usage { struct Test { std::vector<int> myVec; std::vector<int> someOtherVec; bool shouldThrow; void run() { shouldThrow = true; try { SomeFuncThatShouldBehaveAtomicallyInCaseOfExceptionsUsingScopeGuardsThatDoesNOTRollbackIfAdquireThrows(); } catch (...) { AssertMsg( myVec.size() == 0 && someOtherVec.size() == 0 , "rollback did not work"); } shouldThrow = false; SomeFuncThatShouldBehaveAtomicallyInCaseOfExceptionsUsingScopeGuardsThatDoesNOTRollbackIfAdquireThrows(); AssertMsg( myVec.size() == 1 && someOtherVec.size() == 1 , "unexpected end state"); shouldThrow = true; myVec.clear(); someOtherVec.clear(); try { SomeFuncThatShouldBehaveAtomicallyInCaseOfExceptionsUsingScopeGuardsThatDoesRollbackIfAdquireThrows(); } catch (...) { AssertMsg( myVec.size() == 0 && someOtherVec.size() == 0 , "rollback did not work"); } } void SomeFuncThatShouldBehaveAtomicallyInCaseOfExceptionsUsingScopeGuardsThatDoesNOTRollbackIfAdquireThrows() //throw() { myVec.push_back(42);</code>
以上是以下是一些標題選項,每個標題都強調文章的不同面向: 選項 1:重點關注概念和 C 11 功能: * C 11 中的 ScopeGuard:簡單的錯誤處理,但有哪些注意事項的詳細內容。更多資訊請關注PHP中文網其他相關文章!