|
| 1 | +/* |
| 2 | +* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. |
| 3 | +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 4 | +* |
| 5 | +* This code is free software; you can redistribute it and/or modify it |
| 6 | +* under the terms of the GNU General Public License version 2 only, as |
| 7 | +* published by the Free Software Foundation. |
| 8 | +* |
| 9 | +* This code is distributed in the hope that it will be useful, but WITHOUT |
| 10 | +* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 11 | +* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 12 | +* version 2 for more details (a copy is included in the LICENSE file that |
| 13 | +* accompanied this code). |
| 14 | +* |
| 15 | +* You should have received a copy of the GNU General Public License version |
| 16 | +* 2 along with this work; if not, write to the Free Software Foundation, |
| 17 | +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
| 18 | +* |
| 19 | +* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
| 20 | +* or visit www.oracle.com if you need additional information or have any |
| 21 | +* questions. |
| 22 | +* |
| 23 | +*/ |
| 24 | + |
| 25 | +#ifndef SHARE_UTILITIES_STABLEVALUE_HPP |
| 26 | +#define SHARE_UTILITIES_STABLEVALUE_HPP |
| 27 | + |
| 28 | +#include "globalDefinitions.hpp" |
| 29 | +#include <type_traits> |
| 30 | + |
| 31 | +// The purpose of this class is to defer initialization of a T to a later point in time, |
| 32 | +// and then to never deallocate it. This is mainly useful for deferring the initialization of |
| 33 | +// static fields in classes, in order to avoid "Static Initialization Order Fiasco". |
| 34 | +template<typename T> |
| 35 | +class Deferred { |
| 36 | + union { |
| 37 | + T _t; |
| 38 | + }; |
| 39 | + |
| 40 | + DEBUG_ONLY(bool _initialized); |
| 41 | + |
| 42 | +public: |
| 43 | + NONCOPYABLE(Deferred); |
| 44 | + |
| 45 | + Deferred() |
| 46 | + DEBUG_ONLY(: _initialized(false)) { |
| 47 | + // Do not construct value, on purpose. |
| 48 | + } |
| 49 | + |
| 50 | + ~Deferred() { |
| 51 | + // Do not destruct value, on purpose. |
| 52 | + } |
| 53 | + |
| 54 | + T* get() { |
| 55 | + assert(_initialized, "must be initialized before access"); |
| 56 | + return &_t; |
| 57 | + } |
| 58 | + |
| 59 | + T& operator*() { |
| 60 | + return *get(); |
| 61 | + } |
| 62 | + |
| 63 | + T* operator->() { |
| 64 | + return get(); |
| 65 | + } |
| 66 | + |
| 67 | + template<typename... Ts> |
| 68 | + void initialize(Ts&... args) { |
| 69 | + assert(!_initialized, "Double initialization forbidden"); |
| 70 | + DEBUG_ONLY(_initialized = true); |
| 71 | + using NCVP = std::add_pointer_t<std::remove_cv_t<T>>; |
| 72 | + ::new (const_cast<NCVP>(get())) T(args...); |
| 73 | + } |
| 74 | +}; |
| 75 | + |
| 76 | +#endif // SHARE_UTILITIES_STABLEVALUE_HPP |
0 commit comments