blob: 34a4050012ea876552f469c2d27832418e7a2fdc [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 *
6*/
7
8#pragma once
9
10#include <functional>
11
12class UniqueResource {
13public:
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
23private:
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
33inline auto make_unique_resource(UniqueResource::Func&& init, UniqueResource::Func&& cleanup)
34{
35 return UniqueResource(std::move(init), std::move(cleanup));
36}