|
| 1 | +/******************************************************************************** |
| 2 | + * Copyright (C) 2023 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH * |
| 3 | + * * |
| 4 | + * This software is distributed under the terms of the * |
| 5 | + * GNU Lesser General Public Licence (LGPL) version 3, * |
| 6 | + * copied verbatim in the file "LICENSE" * |
| 7 | + ********************************************************************************/ |
| 8 | + |
| 9 | +#ifndef FAIRROOT_MEMORY_H_ |
| 10 | +#define FAIRROOT_MEMORY_H_ |
| 11 | + |
| 12 | +#include <memory> |
| 13 | +#include <optional> |
| 14 | + |
| 15 | +/** |
| 16 | + * \brief Internal implementation details |
| 17 | + * |
| 18 | + * Any declarations in here are strictly for internal usage. |
| 19 | + * They may never enter public APIs. |
| 20 | + * |
| 21 | + * \note Anything in here can change at any time without notice! |
| 22 | + */ |
| 23 | +namespace fairroot::detail |
| 24 | +{ |
| 25 | + |
| 26 | +template<typename T, typename Deleter = std::default_delete<T>> |
| 27 | +struct optional_deleter |
| 28 | +{ |
| 29 | + std::optional<Deleter> deleter{std::in_place}; |
| 30 | + |
| 31 | + optional_deleter() = default; |
| 32 | + optional_deleter(const Deleter& x) |
| 33 | + : deleter(std::in_place, x) |
| 34 | + {} |
| 35 | + optional_deleter(std::nullopt_t) |
| 36 | + : deleter() |
| 37 | + {} |
| 38 | + |
| 39 | + void operator()(T* ptr) const |
| 40 | + { |
| 41 | + if (deleter) { |
| 42 | + (*deleter)(ptr); |
| 43 | + } |
| 44 | + } |
| 45 | +}; |
| 46 | + |
| 47 | +/** |
| 48 | + * \brief unique_ptr that alternatively can hold a reference |
| 49 | + * |
| 50 | + * In rare cases we need a unique_ptr that can alternatively |
| 51 | + * contain a reference (and thus not delete its content |
| 52 | + * on destruction). |
| 53 | + * |
| 54 | + * \note Think twice before using this! |
| 55 | + * |
| 56 | + * It's mostly meant for cases, where FairRoot has a public API |
| 57 | + * that enforces this behaviour. This should be deprecated and |
| 58 | + * removed sooner than later. |
| 59 | + */ |
| 60 | +template<typename T, typename Deleter = std::default_delete<T>> |
| 61 | +using maybe_owning_ptr = std::unique_ptr<T, optional_deleter<T, Deleter>>; |
| 62 | + |
| 63 | +inline constexpr auto non_owning = std::nullopt; |
| 64 | + |
| 65 | +} // namespace fairroot::detail |
| 66 | + |
| 67 | +#endif |
0 commit comments