亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

最簡單,最整潔的C ++ 11 ScopeGuard

最簡單,最整潔的C ++ 11 ScopeGuard

C++
汪汪一只貓 2019-11-29 15:35:04
我試圖基于Alexandrescu概念但使用c ++ 11習慣用法編寫一個簡單的ScopeGuard。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 );    }}這是用法: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();}因為我的版本比大多數示例(例如Boost ScopeExit)短得多,所以我想知道我要保留哪些專業。希望我在80/20的情況下(其中80%的代碼具有20%的代碼行的整潔度),但我忍不住想知道我是否缺少一些重要的東西,或者是否有一些不足之處提到此版本的ScopeGuard習慣用法
查看完整描述

3 回答

  • 3 回答
  • 0 關注
  • 1026 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號