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 ); }
};
}
#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.