Jan Kundrát | 6070445 | 2019-04-11 14:18:29 +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 | * |
| 6 | */ |
| 7 | |
| 8 | #pragma once |
| 9 | |
| 10 | #include <functional> |
| 11 | |
| 12 | class UniqueResource { |
| 13 | public: |
| 14 | using Func = std::function<void()>; |
| 15 | UniqueResource(const UniqueResource& other) = delete; |
| 16 | UniqueResource& operator=(const UniqueResource& other) = delete; |
| 17 | UniqueResource(UniqueResource&& other) = default; |
| 18 | ~UniqueResource() |
| 19 | { |
| 20 | cleanup(); |
| 21 | } |
| 22 | |
| 23 | private: |
| 24 | Func cleanup; |
| 25 | UniqueResource(Func&& init, Func&& cleanup) |
| 26 | : cleanup(std::forward<Func>(cleanup)) |
| 27 | { |
| 28 | init(); |
| 29 | } |
| 30 | friend auto make_unique_resource(Func&& init, Func&& cleanup); |
| 31 | }; |
| 32 | |
| 33 | inline auto make_unique_resource(UniqueResource::Func&& init, UniqueResource::Func&& cleanup) |
| 34 | { |
| 35 | return UniqueResource(std::move(init), std::move(cleanup)); |
| 36 | } |