summaryrefslogtreecommitdiff
path: root/libadhocutil/scopeExit.h
blob: 9d4341eaa12e4d3879af72201c17710bf089ef16 (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
#pragma once

#include "c++11Helpers.h"
#include "visibility.h"
#include <functional>
#include <vector>

namespace AdHoc {

	/// Run code at scope exit.
	class DLL_PUBLIC ScopeExit {
	public:
		/** Callback for code to be run. */
		using Event = std::function<void()>;

		/**
		 * Construct an empty trigger for running code yet to be determined at scope exit
		 */
		ScopeExit();
		/** Construct a trigger for running code at scope exit.
		 * @param pre Run this code (unconditionally) first.
		 * @param success Only run this if the scope is exitted cleanly.
		 * @param failure Only run this if the scope is exitted because of an uncaught exception.
		 * @param post Run this code (unconditionally) last.
		 */
		explicit ScopeExit(const Event & pre, const Event & success = Event(), const Event & failure = Event(),
				const Event & post = Event());
		~ScopeExit();

		/// Standard move/copy support
		SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(ScopeExit);

		/// @cond
		std::vector<Event> onExitPre;
		std::vector<Event> onSuccess;
		std::vector<Event> onFailure;
		std::vector<Event> onExitPost;
		/// @endcond
	};

}