MCRO
C++23 utilities for Unreal Engine.
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages Concepts
Finally.h
Go to the documentation of this file.
1/** @noop License Comment
2 * @file
3 * @copyright
4 * This Source Code is subject to the terms of the Mozilla Public License, v2.0.
5 * If a copy of the MPL was not distributed with this file You can obtain one at
6 * https://mozilla.org/MPL/2.0/
7 *
8 * @author David Mórász
9 * @date 2025
10 */
11
12#pragma once
13#include "CoreMinimal.h"
14
16{
17 /**
18 * @brief
19 * Run arbitrary finalizers on destruction. It has similar purpose to `ON_SCOPE_EXIT`, however FFinally can be
20 * moved around into different scopes, Payload will be only executed if the finalizer hasn't been moved from,
21 * otherwise the payload will be ignored in the source of move assignments
22 *
23 * Usage:
24 * @code
25 * {
26 * FFinally fin([] {...})
27 * Async(EAsyncExecution::ThreadPool, [fin = MoveTemp(fin)]
28 * {
29 * // Payload is executed at the end of this scope
30 * }
31 * // Payload is not executed here
32 * }
33 * @endcode
34 * Finalizers can be moved into nested scopes
35 * @code
36 * {
37 * FFinally fin([] {...})
38 * Async(EAsyncExecution::ThreadPool, [fin = MoveTemp(fin)] mutable
39 * {
40 * AsyncTask(ENamedThreads::GameThread, [fin = MoveTemp(fin)]
41 * {
42 * // Payload is executed at the end of this scope
43 * }
44 * // Payload is not executed here
45 * }
46 * // Payload is not executed here
47 * }
48 * @endcode
49 */
50 struct FFinally : FNoncopyable
51 {
52 private:
53 TUniqueFunction<void()> Payload;
54 bool bIsValid = true;
55
56 public:
57 FFinally(TUniqueFunction<void()>&& payload) : Payload(MoveTemp(payload)) {}
58 FFinally(FFinally&& from) noexcept : Payload(MoveTemp(from.Payload))
59 {
60 from.bIsValid = false;
61 }
62
64 {
65 if(bIsValid) Payload();
66 }
67 };
68
69 /**
70 * @warning
71 * Do not use this directly, use FINALLY macro. Similar intentions to ON_SCOPE_EXIT but gives more freedom
72 */
74 {
75 FFinally operator+(TUniqueFunction<void()>&& payload)
76 {
77 return FFinally(MoveTemp(payload));
78 }
79 };
80}
81
82/**
83 * A more convenient way to use `FFinally`.
84 *
85 * @code
86 * auto fin = FINALLY(=, this) mutable
87 * {
88 * ...
89 * };
90 * AsyncTask(ENamedThreads::GameThread, [fin = MoveTemp(fin)]
91 * {
92 * // Payload is executed at the end of this scope
93 * }
94 * @endcode
95 */
96#define FINALLY(...) Mcro::Finally::FFinallySyntaxSupport() + [__VA_ARGS__]()
FFinally operator+(TUniqueFunction< void()> &&payload)
Definition Finally.h:75
Run arbitrary finalizers on destruction. It has similar purpose to ON_SCOPE_EXIT, however FFinally ca...
Definition Finally.h:51
FFinally(TUniqueFunction< void()> &&payload)
Definition Finally.h:57
FFinally(FFinally &&from) noexcept
Definition Finally.h:58