sessiond: open_packets: use user_space_consumer_channel_keys util
[lttng-tools.git] / src / common / make-unique-wrapper.hpp
CommitLineData
8802d23b
JG
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>
a0a4f314 12#include <common/meta-helpers.hpp>
8802d23b
JG
13
14#include <memory>
15
16namespace 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.
74021af6 38 * If you need to return this unique_ptr instance, you should consider writing
8802d23b
JG
39 * a proper, idiomatic, wrapper.
40 */
41
f053d40c 42namespace memory {
8802d23b
JG
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 */
49template <class Type>
50void free(Type *ptr)
51{
52 std::free(ptr);
53}
303ac4ed 54} /* namespace memory */
8802d23b
JG
55
56template <typename WrappedType, void (*DeleterFunc)(WrappedType *)>
28f23191 57std::unique_ptr<WrappedType,
f053d40c 58 typename memory::create_deleter_class<WrappedType, DeleterFunc>::deleter>
799462ff 59make_unique_wrapper(WrappedType *instance = nullptr)
8802d23b 60{
f053d40c 61 const memory::create_deleter_class<WrappedType, DeleterFunc> unique_deleter;
8802d23b
JG
62
63 return unique_deleter(instance);
64}
65
66} /* namespace lttng */
67
68#endif /* LTTNG_MAKE_UNIQUE_WRAPPER_H */
This page took 0.04536 seconds and 4 git commands to generate.