What is ScopeGuard in C ++?

I get the impression that this is a C ++ class contained in a library written by a third party. I tried a google search and I found one post that said it was a good idea to use it. However, he could not accurately describe what it is and how I can include it in my code. Thank you

+4
source share
2 answers

ScopeGuardIt was once a special realization of the region’s guards Peter Margineyan and Andrei Alexandrescu . The idea is to allow the destructor of the security object to trigger the user-specified cleanup action at the end of the scope (read: block), unless the area protector is rejected. Marginean came up with the ingenious idea of ​​declaring a scope security object for C ++ 03, based on extending the link's lifespan const.

Today, “protecting the area” is more of a general idea.

RAII ( , ), , , , for , for , , , , RAII. for , . , RAII.


++ 11 std::function, .

:

#include <functional>       // std::function
#include <utility>          // std::move

namespace my {
    using std::function;
    using std::move;

    class Non_copyable
    {
    private:
        auto operator=( Non_copyable const& ) -> Non_copyable& = delete;
        Non_copyable( Non_copyable const& ) = delete;
    public:
        auto operator=( Non_copyable&& ) -> Non_copyable& = default;
        Non_copyable() = default;
        Non_copyable( Non_copyable&& ) = default;
    };

    class Scope_guard
        : public Non_copyable
    {
    private:
        function<void()>    cleanup_;

    public:
        friend
        void dismiss( Scope_guard& g ) { g.cleanup_ = []{}; }

        ~Scope_guard() { cleanup_(); }

        template< class Func >
        Scope_guard( Func const& cleanup )
            : cleanup_( cleanup )
        {}

        Scope_guard( Scope_guard&& other )
            : cleanup_( move( other.cleanup_ ) )
        { dismiss( other ); }
    };

}  // namespace my

#include <iostream>
void foo() {}
auto main() -> int
{
    using namespace std;
    my::Scope_guard const final_action = []{ wclog << "Finished! (Exit from main.)\n"; };

    wcout << "The answer is probably " << 6*7 << ".\n";
}

function , , Scope_guard . , , , , , , , , ++ 11 auto , , factory . - ++ 11 , ++ 03.

+8

, . / ( , ), . unique_lock ++ 11 .

, unique_lock :

void foo()
{
    myMutex.lock();
    bar();
    myMutex.unlock();
}

:

void foo()
{
    unique_lock<mutex> ulock(myMutex);
    bar();
}

, , bar ? myMutex , ​​ . , , unique_lock . bar , unique_lock , , , . bar try/catch .

+1

All Articles