2 * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
8 #ifndef LTTNG_MAKE_UNIQUE_WRAPPER_H
9 #define LTTNG_MAKE_UNIQUE_WRAPPER_H
11 #include <common/macros.hpp>
12 #include <common/meta-helpers.hpp>
19 * make_unique_wrapper is intended to facilitate the use of std::unique_ptr
20 * to wrap C-style APIs that don't provide RAII resource management facilities.
25 * struct my_c_struct {
29 * struct my_c_struct *create_my_c_struct(void);
30 * void destroy_my_c_struct(struct my_c_struct *value);
32 * // Creating a unique_ptr to my_c_struct.
33 * auto safe_c_struct =
34 * lttng::make_unique_wrapper<my_c_struct, destroy_my_c_struct>(
35 * create_my_c_struct());
37 * Note that this facility is intended for use in the scope of a function.
38 * If you need to return this unique_ptr instance, you should consider writing
39 * a proper, idiomatic, wrapper.
44 * 'free' is a utility function for use with make_unique_wrapper. It makes it easier to
45 * wrap raw pointers that have to be deleted with `free`. Using libc's 'free' as
46 * a make_unique_wrapper template argument will result in an error as 'WrappedType *' will
47 * not match free's 'void *' argument.
54 } /* namespace memory */
56 template <typename WrappedType, void (*DeleterFunc)(WrappedType *)>
57 std::unique_ptr<WrappedType,
58 typename memory::create_deleter_class<WrappedType, DeleterFunc>::deleter>
59 make_unique_wrapper(WrappedType *instance = nullptr)
61 const memory::create_deleter_class<WrappedType, DeleterFunc> unique_deleter;
63 return unique_deleter(instance);
66 } /* namespace lttng */
68 #endif /* LTTNG_MAKE_UNIQUE_WRAPPER_H */