blob: 3af69ca8f4e29166c6b1a30f550f0415a7570d8b [file] [log] [blame]
Václav Kubernátf2241b82021-03-29 03:55:04 +02001/*
2 * Copyright (C) 2017-2019 CESNET, https://photonics.cesnet.cz/
3 *
4 * Written by Jan Kundrát <jan.kundrat@cesnet.cz>
5 *
Tomáš Pecka18df5d02023-04-14 11:23:05 +02006 */
Václav Kubernátf2241b82021-03-29 03:55:04 +02007
8#pragma once
9
10#include <functional>
11
Tomáš Pecka18df5d02023-04-14 11:23:05 +020012namespace velia::utils {
13
Václav Kubernátf2241b82021-03-29 03:55:04 +020014class UniqueResource {
15public:
16 using Func = std::function<void()>;
17 UniqueResource(const UniqueResource& other) = delete;
18 UniqueResource& operator=(const UniqueResource& other) = delete;
19 UniqueResource(UniqueResource&& other) = default;
20 ~UniqueResource()
21 {
22 cleanup();
23 }
24
25private:
26 Func cleanup;
27 UniqueResource(Func&& init, Func&& cleanup)
28 : cleanup(std::forward<Func>(cleanup))
29 {
30 init();
31 }
32 friend auto make_unique_resource(Func&& init, Func&& cleanup);
33};
34
35inline auto make_unique_resource(UniqueResource::Func&& init, UniqueResource::Func&& cleanup)
36{
37 return UniqueResource(std::move(init), std::move(cleanup));
38}
Tomáš Pecka18df5d02023-04-14 11:23:05 +020039}