• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef COMMON_COMPONENTS_BASE_IMMORTAL_WRAPPER_H
17 #define COMMON_COMPONENTS_BASE_IMMORTAL_WRAPPER_H
18 
19 #include <new>
20 #include <utility>
21 
22 namespace common {
23 // Utility class ensuring ordered destruction of static global objects to prevent dependency-related issues during
24 // program termination.
25 template<class Type>
26 class ImmortalWrapper {
27 public:
28     template<class... Args>
ImmortalWrapper(Args &&...args)29     ImmortalWrapper(Args&&... args)
30     {
31         new (buffer_) Type(std::forward<Args>(args)...);
32     }
33     ImmortalWrapper(const ImmortalWrapper&) = delete;
34     ImmortalWrapper& operator=(const ImmortalWrapper&) = delete;
35     ~ImmortalWrapper() = default;
36     inline typename std::add_pointer<Type>::type operator->()
37     {
38         return reinterpret_cast<typename std::add_pointer<Type>::type>(buffer_);
39     }
40 
41     inline typename std::add_lvalue_reference<Type>::type operator*()
42     {
43         return reinterpret_cast<typename std::add_lvalue_reference<Type>::type>(buffer_);
44     }
45 
46 private:
47     alignas(Type) unsigned char buffer_[sizeof(Type)] = { 0 };
48 };
49 } // namespace common
50 #endif // COMMON_COMPONENTS_BASE_IMMORTAL_WRAPPER_H
51