Václav Kubernát | f2241b8 | 2021-03-29 03:55:04 +0200 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2017-2019 CESNET, https://photonics.cesnet.cz/ |
| 3 | * |
| 4 | * Written by Jan Kundrát <jan.kundrat@cesnet.cz> |
| 5 | * |
Tomáš Pecka | 18df5d0 | 2023-04-14 11:23:05 +0200 | [diff] [blame^] | 6 | */ |
Václav Kubernát | f2241b8 | 2021-03-29 03:55:04 +0200 | [diff] [blame] | 7 | |
| 8 | #pragma once |
| 9 | |
| 10 | #include <functional> |
| 11 | |
Tomáš Pecka | 18df5d0 | 2023-04-14 11:23:05 +0200 | [diff] [blame^] | 12 | namespace velia::utils { |
| 13 | |
Václav Kubernát | f2241b8 | 2021-03-29 03:55:04 +0200 | [diff] [blame] | 14 | class UniqueResource { |
| 15 | public: |
| 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 | |
| 25 | private: |
| 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 | |
| 35 | inline auto make_unique_resource(UniqueResource::Func&& init, UniqueResource::Func&& cleanup) |
| 36 | { |
| 37 | return UniqueResource(std::move(init), std::move(cleanup)); |
| 38 | } |
Tomáš Pecka | 18df5d0 | 2023-04-14 11:23:05 +0200 | [diff] [blame^] | 39 | } |