sessiond: open_packets: use user_space_consumer_channel_keys util
[lttng-tools.git] / src / common / make-unique-wrapper.hpp
1 /*
2 * Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 *
6 */
7
8 #ifndef LTTNG_MAKE_UNIQUE_WRAPPER_H
9 #define LTTNG_MAKE_UNIQUE_WRAPPER_H
10
11 #include <common/macros.hpp>
12 #include <common/meta-helpers.hpp>
13
14 #include <memory>
15
16 namespace lttng {
17
18 /*
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.
21 *
22 * Usage example:
23 *
24 * // API
25 * struct my_c_struct {
26 * // ...
27 * };
28 *
29 * struct my_c_struct *create_my_c_struct(void);
30 * void destroy_my_c_struct(struct my_c_struct *value);
31 *
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());
36 *
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.
40 */
41
42 namespace memory {
43 /*
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.
48 */
49 template <class Type>
50 void free(Type *ptr)
51 {
52 std::free(ptr);
53 }
54 } /* namespace memory */
55
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)
60 {
61 const memory::create_deleter_class<WrappedType, DeleterFunc> unique_deleter;
62
63 return unique_deleter(instance);
64 }
65
66 } /* namespace lttng */
67
68 #endif /* LTTNG_MAKE_UNIQUE_WRAPPER_H */
This page took 0.030019 seconds and 4 git commands to generate.