> 백엔드 개발 > C++ > 본문

다음은 기사의 내용과 일치하는 몇 가지 영어 제목입니다. 간결한 제목(짧고 직접적): * C 11 관용구를 사용하여 간단한 ScopeGuard를 구축하는 방법은 무엇입니까? * C 11에서 간단한 ScopeGuard 구현: 실용적인 접근 방식 * C 11 ScopeGuard: 간결하고 실용적인 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>
로그인 후 복사

장점:

  • 간단하고 사용하기 쉬움
  • 간결한 코드
  • 예외 처리 지원

잠재적 문제:

  • advice 람다 함수에서 예외가 발생하는 경우 릴리스 람다 함수는 ScopeGuard를 완전히 구성하지 않기 때문에 호출되지 않습니다.
  • 정리 기능에서 예외가 발생하면 프로그램이 예기치 않게 종료됩니다.

위 내용은 다음은 기사의 내용과 일치하는 몇 가지 영어 제목입니다. 간결한 제목(짧고 직접적): * C 11 관용구를 사용하여 간단한 ScopeGuard를 구축하는 방법은 무엇입니까? * C 11에서 간단한 ScopeGuard 구현: 실용적인 접근 방식 * C 11 ScopeGuard: 간결하고 실용적인 I의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!