问题:
如何使用 C 11 惯用法编写基于 Alexandrescu 概念的简单 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中文网其他相关文章!