Utility function for RAII-like init/cleanup handling
This is a poor man's copy of the P0052's make_unique_resource
reimplementation which was taken from the (internal, for now)
cla-sysrepo project.
Change-Id: If639872cc3c9f0779da57a821dd7eb81203a0b9c
diff --git a/src/UniqueResource.h b/src/UniqueResource.h
new file mode 100644
index 0000000..34a4050
--- /dev/null
+++ b/src/UniqueResource.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017-2019 CESNET, https://photonics.cesnet.cz/
+ *
+ * Written by Jan Kundrát <jan.kundrat@cesnet.cz>
+ *
+*/
+
+#pragma once
+
+#include <functional>
+
+class UniqueResource {
+public:
+ using Func = std::function<void()>;
+ UniqueResource(const UniqueResource& other) = delete;
+ UniqueResource& operator=(const UniqueResource& other) = delete;
+ UniqueResource(UniqueResource&& other) = default;
+ ~UniqueResource()
+ {
+ cleanup();
+ }
+
+private:
+ Func cleanup;
+ UniqueResource(Func&& init, Func&& cleanup)
+ : cleanup(std::forward<Func>(cleanup))
+ {
+ init();
+ }
+ friend auto make_unique_resource(Func&& init, Func&& cleanup);
+};
+
+inline auto make_unique_resource(UniqueResource::Func&& init, UniqueResource::Func&& cleanup)
+{
+ return UniqueResource(std::move(init), std::move(cleanup));
+}