summaryrefslogtreecommitdiff
path: root/zen/scope_guard.h
blob: 81f47f873934b9ff7128280a5093d455af2d0152 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// **************************************************************************
// * This file is part of the zenXML project. It is distributed under the   *
// * Boost Software License: http://www.boost.org/LICENSE_1_0.txt           *
// * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved        *
// **************************************************************************

#ifndef ZEN_SCOPEGUARD_8971632487321434
#define ZEN_SCOPEGUARD_8971632487321434

#include <cassert>

//best of Zen, Loki and C++11

namespace zen
{
//Scope Guard
/*
    zen::ScopeGuard lockAio = zen::makeGuard([&]() { ::CancelIo(hDir); });
		...
	lockAio.dismiss();
*/

//Scope Exit
/*
	ZEN_ON_SCOPE_EXIT(::CloseHandle(hDir));
*/

class ScopeGuardBase
{
public:
    void dismiss() { dismissed_ = true; }

protected:
    ScopeGuardBase() : dismissed_(false) {}
    ScopeGuardBase(ScopeGuardBase&& other) : dismissed_(other.dismissed_) { other.dismiss(); } //take over responsibility
    ~ScopeGuardBase() {}

    bool isDismissed() const { return dismissed_; }

private:
    ScopeGuardBase(const ScopeGuardBase&); //delete
    ScopeGuardBase& operator=(const ScopeGuardBase&); // = delete;

    bool dismissed_;
};


template <typename F>
class ScopeGuardImpl : public ScopeGuardBase
{
public:
    explicit ScopeGuardImpl(const F& fun) : fun_(fun) {}
    explicit ScopeGuardImpl(F&& fun) : fun_(std::move(fun)) {}
    ScopeGuardImpl(ScopeGuardImpl&& other) : ScopeGuardBase(std::move(other)), fun_(std::move(other.fun_)) {}

    ~ScopeGuardImpl()
    {
        if (!this->isDismissed())
            try
            {
                fun_();
            }
            catch (...) { assert(false); }
    }

private:
    F fun_;
};

typedef ScopeGuardBase&& ScopeGuard;

template <class F> inline
ScopeGuardImpl<typename std::decay<F>::type> makeGuard(F&& fun) { return ScopeGuardImpl<typename std::decay<F>::type>(std::forward<F>(fun)); }
}

#define ZEN_CONCAT_SUB(X, Y) X ## Y
#define ZEN_CONCAT(X, Y) ZEN_CONCAT_SUB(X, Y)

#define ZEN_ON_SCOPE_EXIT(X) zen::ScopeGuard ZEN_CONCAT(dummy, __LINE__) = zen::makeGuard([&]{ X; }); (void)ZEN_CONCAT(dummy, __LINE__);

#endif //ZEN_SCOPEGUARD_8971632487321434
bgstack15