搜索
首页后端开发C++以下是一些标题选项,每个标题都强调文章的不同方面: 选项 1:重点关注概念和 C 11 功能: * C 11 中的 ScopeGuard:简单的错误处理,但有哪些注意事项

Here are a few title options, each emphasizing a different aspect of the article:

Option 1: Focusing on the concept and C  11 feature:

* ScopeGuard in C  11: Simple Error Handling, But Which Caveats? 

Option 2: Highlighting the simplicity and limitatio

最简单、最简洁的 C 11 ScopeGuard

在 C 11 中,有一个简单的习惯用法可以实现 ScopeGuard,从而简化错误和资源处理。下面是一个简单的解释和实现:

概念:

ScopeGuard 是一个 C 类,它提供了一种定义代码块的方法,当创建守卫的范围退出。这样可以轻松进行清理和错误处理,确保即使在特殊情况下也能释放资源或采取操作。

实现:

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

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

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

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

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

    template<typename rlambda>
    const ScopeGuard& makeScopeGuard(const rLambda& _r)
    {
        return ScopeGuard(_r );
    }
}</typename></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();
}</int></int></code>

在此示例中,ScopeGuard 习惯用法用于确保即使在函数范围内引发异常,也会执行清理操作(从向量中弹出元素)。

简单性和局限性:

ScopeGuard 习惯用法的这种实现相对简单和简洁,使其易于使用和理解。然而,原问题的作者也对潜在的缺陷或缺失的专业提出了担忧。让我们解决这些问题:

  • 完美转发: 该实现并未充分利用 C 11 完美转发技术。这在 makeScopeGuard 函数中很明显,该函数使用左值引用而不是 lambda 参数的通用引用。使用通用引用将提供更大的灵活性并支持右值 lambda。
  • 如果获取抛出异常则回滚: 原始实现不处理“获取”lambda 抛出异常的情况。如果获取 lambda 失败,则永远不会调用回滚 lambda,从而使代码处于不一致的状态。

为了解决这些问题,以下是 ScopeGuard 实现和用法的更新版本:

<code class="cpp">namespace RAII
{
    template
    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
            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
            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
    ScopeGuard // return by value is the preferred C++11 way.
    makeScopeGuardThatDoesNOTRollbackIfAdquireThrows( aLambda&& _a , rLambda&& _r) // again perfect forwarding
    {
        return ScopeGuard( std::forward<alambda>(_a) , std::forward<rlambda>(_r )); // *** no longer UB, because we're returning by value
    }

    template
    ScopeGuard // return by value is the preferred C++11 way.
    makeScopeGuardThatDoesRollbackIfAdquireThrows( aLambda&& _a , rLambda&& _r) // again perfect forwarding
    {
        auto scope = ScopeGuard(std::forward<rlambda>(_r )); // *** no longer UB, because we're returning by value
        _a();
        return scope;
    }

    template<typename rlambda>
    ScopeGuard makeScopeGuard(rLambda&& _r)
    {
        return ScopeGuard( 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);</int></int></rlambda></typename></rlambda></rlambda></alambda></adquirelambda></l></adquirelambda></code>

以上是以下是一些标题选项,每个标题都强调文章的不同方面: 选项 1:重点关注概念和 C 11 功能: * C 11 中的 ScopeGuard:简单的错误处理,但有哪些注意事项的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
继续使用C:耐力的原因继续使用C:耐力的原因Apr 11, 2025 am 12:02 AM

C 持续使用的理由包括其高性能、广泛应用和不断演进的特性。1)高效性能:通过直接操作内存和硬件,C 在系统编程和高性能计算中表现出色。2)广泛应用:在游戏开发、嵌入式系统等领域大放异彩。3)不断演进:自1983年发布以来,C 持续增加新特性,保持其竞争力。

C和XML的未来:新兴趋势和技术C和XML的未来:新兴趋势和技术Apr 10, 2025 am 09:28 AM

C 和XML的未来发展趋势分别为:1)C 将通过C 20和C 23标准引入模块、概念和协程等新特性,提升编程效率和安全性;2)XML将继续在数据交换和配置文件中占据重要地位,但会面临JSON和YAML的挑战,并朝着更简洁和易解析的方向发展,如XMLSchema1.1和XPath3.1的改进。

现代C设计模式:构建可扩展和可维护的软件现代C设计模式:构建可扩展和可维护的软件Apr 09, 2025 am 12:06 AM

现代C 设计模式利用C 11及以后的新特性实现,帮助构建更灵活、高效的软件。1)使用lambda表达式和std::function简化观察者模式。2)通过移动语义和完美转发优化性能。3)智能指针确保类型安全和资源管理。

C多线程和并发:掌握并行编程C多线程和并发:掌握并行编程Apr 08, 2025 am 12:10 AM

C 多线程和并发编程的核心概念包括线程的创建与管理、同步与互斥、条件变量、线程池、异步编程、常见错误与调试技巧以及性能优化与最佳实践。1)创建线程使用std::thread类,示例展示了如何创建并等待线程完成。2)同步与互斥使用std::mutex和std::lock_guard保护共享资源,避免数据竞争。3)条件变量通过std::condition_variable实现线程间的通信和同步。4)线程池示例展示了如何使用ThreadPool类并行处理任务,提高效率。5)异步编程使用std::as

C深度潜水:掌握记忆管理,指针和模板C深度潜水:掌握记忆管理,指针和模板Apr 07, 2025 am 12:11 AM

C 的内存管理、指针和模板是核心特性。1.内存管理通过new和delete手动分配和释放内存,需注意堆和栈的区别。2.指针允许直接操作内存地址,使用需谨慎,智能指针可简化管理。3.模板实现泛型编程,提高代码重用性和灵活性,需理解类型推导和特化。

C和系统编程:低级控制和硬件交互C和系统编程:低级控制和硬件交互Apr 06, 2025 am 12:06 AM

C 适合系统编程和硬件交互,因为它提供了接近硬件的控制能力和面向对象编程的强大特性。1)C 通过指针、内存管理和位操作等低级特性,实现高效的系统级操作。2)硬件交互通过设备驱动程序实现,C 可以编写这些驱动程序,处理与硬件设备的通信。

使用C的游戏开发:构建高性能游戏和模拟使用C的游戏开发:构建高性能游戏和模拟Apr 05, 2025 am 12:11 AM

C 适合构建高性能游戏和仿真系统,因为它提供接近硬件的控制和高效性能。1)内存管理:手动控制减少碎片,提高性能。2)编译时优化:内联函数和循环展开提升运行速度。3)低级操作:直接访问硬件,优化图形和物理计算。

C语言文件操作难题的幕后真相C语言文件操作难题的幕后真相Apr 04, 2025 am 11:24 AM

文件操作难题的真相:文件打开失败:权限不足、路径错误、文件被占用。数据写入失败:缓冲区已满、文件不可写、磁盘空间不足。其他常见问题:文件遍历缓慢、文本文件编码不正确、二进制文件读取错误。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)