Lightweight 0.20261105.1
Loading...
Searching...
No Matches
ImmortalInstance.hpp
1// SPDX-License-Identifier: Apache-2.0
2
3#pragma once
4
5#include <array>
6#include <cstddef>
7#include <memory>
8#include <utility>
9
10namespace Lightweight::detail
11{
12
13/// Constructs a @p T in static storage on first use and never destroys it.
14///
15/// For state that destructors of other static objects still use during static destruction, whose
16/// order relative to this instance no translation unit controls.
17///
18/// There is one instance per @p T and argument type list, since each is its own specialization, so
19/// every call site for the same @p T must pass arguments of the same types.
20///
21/// @param args The constructor arguments, used by the first call only.
22/// @return The one instance.
23template <typename T, typename... Args>
24T& ImmortalInstance(Args&&... args)
25{
26 alignas(T) static std::array<std::byte, sizeof(T)> storage {};
27 static T& instance = *std::construct_at(reinterpret_cast<T*>(storage.data()), std::forward<Args>(args)...);
28 return instance;
29}
30
31} // namespace Lightweight::detail