Skip to content

Commit 33450dd

Browse files
committed
Implemented scoped defer utility
1 parent f4b1f08 commit 33450dd

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

engine/utils/Defer.h

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//
2+
// Copyright (c) 2023 Jonathan Moallem (@J-Mo63) & Aryeh Zinn (@Raelr)
3+
//
4+
// This code is released under an unmodified zlib license.
5+
// For conditions of distribution and use, please see:
6+
// https://opensource.org/licenses/Zlib
7+
//
8+
9+
#ifndef SIEGE_ENGINE_DEFER_H
10+
#define SIEGE_ENGINE_DEFER_H
11+
12+
#include <functional>
13+
14+
#include "Macros.h"
15+
16+
namespace Siege
17+
{
18+
19+
/**
20+
* A basic deferred call object implementation that executes its provided callable on scope exit.
21+
*/
22+
struct ScopedDefer
23+
{
24+
/**
25+
* Explicitly deleted zero-param constructor
26+
*/
27+
ScopedDefer() = delete;
28+
29+
/**
30+
* Constructor, specifying owned callable
31+
* @param callable - the void-returning, parameterless callable to execute
32+
*/
33+
explicit ScopedDefer(const std::function<void()>& callable) : callable(callable) {}
34+
35+
/**
36+
* Destructor, executing callable on scope exit
37+
*/
38+
~ScopedDefer()
39+
{
40+
callable();
41+
}
42+
43+
/**
44+
* Held void-retuning, parameterless callable
45+
*/
46+
std::function<void()> callable;
47+
};
48+
49+
#define _DEFER_VAR_NAME CONCAT_SYMBOL(_defer_, __COUNTER__)
50+
#define defer(callable) auto _DEFER_VAR_NAME = Siege::ScopedDefer(callable)
51+
52+
} // namespace Siege
53+
54+
#endif // SIEGE_ENGINE_DEFER_H

0 commit comments

Comments
 (0)