ML Reference
mlScopeGuard.h
Go to the documentation of this file.
1/*************************************************************************************
2**
3** Copyright 2013, MeVis Medical Solutions AG
4**
5** The user may use this file in accordance with the license agreement provided with
6** the Software or, alternatively, in accordance with the terms contained in a
7** written agreement between the user and MeVis Medical Solutions AG.
8**
9** For further information use the contact form at https://www.mevislab.de/contact
10**
11**************************************************************************************/
12
13#pragma once
14
15#include "mlTypeDefs.h"
16
17#include <utility>
18
24#define ML_UTILITIES_CONCATENATE_IMPL(s1,s2) s1##s2
25#define ML_UTILITIES_CONCATENATE(s1,s2) ML_UTILITIES_CONCATENATE_IMPL(s1,s2)
26
27// Some compiler does not support __COUNTER__ so there is an alternative
28// implementation with __LINE__
29#ifdef __COUNTER__
30#define ML_UTILITIES_ANONYMOUS_VARIABLE(str)\
31 ML_UTILITIES_CONCATENATE(str,__COUNTER__)
32#else
33#define ML_UTILITIES_ANONYMOUS_VARIABLE(str) \
34 ML_UTILITIES_CONCATENATE(str,__LINE__)
35#endif
36
37ML_START_NAMESPACE
38
39 namespace ScopeGuardDetail
40 {
41 template <class Functor>
43 {
44 public:
45 explicit ScopeGuard(Functor fn)
46 : _f(std::move(fn))
47 , _active(true)
48 {}
49
51 : _f(std::move(rhs._f))
52 , _active(rhs._active)
53 {
54 rhs._active = false;
55 }
56
58 {
59 if (_active)
60 {
61 _f();
62 }
63 }
64
65 void dismiss()
66 {
67 _active = false;
68 }
69
70 private:
71 Functor _f;
72 bool _active;
73
74 ScopeGuard() = delete;
75 ScopeGuard(const ScopeGuard&) = delete;
76 ScopeGuard& operator=(const ScopeGuard&) = delete;
77 };
78
79 enum class ScopeGuardOnExit {};
80
81 template <class Functor>
83 {
84 return ScopeGuard<Functor>(std::forward<Functor>(fn));
85 }
86 }
87
88ML_END_NAMESPACE
89
96#define SCOPE_EXIT \
97 auto ML_UTILITIES_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
98 = ::ML_NAMESPACE::ScopeGuardDetail::ScopeGuardOnExit() + [&]()
99
100
116#define EXPLICIT_SCOPE_EXIT \
117 ::ML_NAMESPACE::ScopeGuardDetail::ScopeGuardOnExit() + [&]()
ScopeGuard< Functor > operator+(ScopeGuardOnExit, Functor &&fn)
STL namespace.