首頁  >  文章  >  後端開發  >  以下是幾個符合文章內容的英文標題: 簡潔的標題(簡短且直接): * 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

以下是幾個符合文章內容的英文標題: 簡潔的標題(簡短且直接): * 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

Linda Hamilton
Linda Hamilton原創
2024-10-26 10:12:03926瀏覽

以下是几个符合文章内容的英文标题:

简洁的标题(简短且直接):

* 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 Implementation

更详细的标题(阐明文章重点):

* C  11 ScopeGuard: A S

C 11 中簡潔實用的ScopeGuard

問題:

如何使用基於Alexcucu簡單ScopeGuard?

回答:

以下是基於C 11 慣用法的ScopeGuard 實現:

<code class="cpp">namespace RAII
{
    template< typename Lambda >
    class ScopeGuard
    {
        mutable bool committed;
        Lambda rollbackLambda; 
        public:

            ScopeGuard( const Lambda&amp; _l) : committed(false) , rollbackLambda(_l) {}

            template< typename AdquireLambda >
            ScopeGuard( const AdquireLambda&amp; _al , const Lambda&amp; _l) : committed(false) , rollbackLambda(_l)
            {
                _al();
            }

            ~ScopeGuard()
            {
                if (!committed)
                    rollbackLambda();
            }
            inline void commit() const { committed = true; }
    };

    template< typename aLambda , typename rLambda>
    const ScopeGuard< rLambda >&amp; makeScopeGuard( const aLambda&amp; _a , const rLambda&amp; _r)
    {
        return ScopeGuard< rLambda >( _a , _r );
    }

    template<typename rLambda>
    const ScopeGuard< rLambda >&amp; makeScopeGuard(const rLambda&amp; _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&amp; a = RAII::makeScopeGuard( [&amp;]() { myVec.pop_back(); } );  

   //sintactically neater, since everything happens in a single line
   const auto&amp; b = RAII::makeScopeGuard( [&amp;]() { someOtherVec.push_back(42); }
                     , [&amp;]() { someOtherVec.pop_back(); } ); 

   b.commit();
   a.commit();
}</code>

優點:

  • 簡單易用
  • 程式碼簡潔
  • 支援異常處理
  • 潛在問題:

      如果adquire lambda 函數拋出異常,則永遠不會呼叫release lambda 函數,因為它永遠不會完全構造ScopeGuard。
    • 如果 cleanup 函數拋出異常,程式將意外終止。

以上是以下是幾個符合文章內容的英文標題: 簡潔的標題(簡短且直接): * 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn