首页 > 后端开发 > C++ > 正文

以下是几个符合文章内容的英文标题: 简洁的标题(简短且直接): * 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
发布: 2024-10-26 10:12:03
原创
925 人浏览过

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

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

* 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

问题:

如何使用 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&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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!