VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
Subscription.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <functional>
4#include <utility>
5
6namespace VoltMod
7{
8
9/**
10 * @brief Owns one registration and releases it on destruction.
11 *
12 * Holding one keeps the registration alive. Store it beside the state captured by its handler so
13 * it unregisters before that state is destroyed:
14 *
15 * @code
16 * class Bhop {
17 * Bhop(GameEvents& events) {
18 * _spawn = events.On<PlayerSpawn>([this](const PlayerSpawn& e) { OnSpawn(e.Slot); });
19 * }
20 * Subscription _spawn;
21 * };
22 * @endcode
23 *
24 * The cleanup callable may hold any registry handle, including non-handle-based registrations
25 * such as hook installs (see VoltMod::HookInterface).
26 *
27 * Move-only. The registry must outlive its Subscription; reverse declaration order provides this
28 * when both are members of one object.
29 *
30 * `<VoltMod/Core/Signals/Subscriptions.hpp>` holds several of them in one member, for an object that
31 * subscribes to a handful of things at once.
32 */
34{
35public:
36 Subscription() = default;
37
38 /** Run @p cleanup on destruction; it captures whatever handle the registry issued. */
39 explicit Subscription(std::move_only_function<void()> cleanup) : _cleanup(std::move(cleanup)) {}
40
42
43 Subscription(Subscription&& other) noexcept : _cleanup(std::exchange(other._cleanup, nullptr)) {}
44
46 {
47 if (this != &other)
48 {
49 Reset();
50 _cleanup = std::exchange(other._cleanup, nullptr);
51 }
52 return *this;
53 }
54
55 Subscription(const Subscription&) = delete;
57
58 /** Release now. Idempotent, and re-entrant: the callable is detached before it runs. */
59 void Reset()
60 {
61 if (auto cleanup = std::exchange(_cleanup, nullptr))
62 {
63 cleanup();
64 }
65 }
66
67 /** True while this holds a live registration. */
68 explicit operator bool() const noexcept { return static_cast<bool>(_cleanup); }
69
70private:
71 std::move_only_function<void()> _cleanup;
72};
73
74} // namespace VoltMod
Owns one registration and releases it on destruction.
Subscription & operator=(Subscription &&other) noexcept
Subscription(std::move_only_function< void()> cleanup)
Subscription(const Subscription &)=delete
Subscription & operator=(const Subscription &)=delete
Subscription(Subscription &&other) noexcept
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56