Gazebo Utils

API Reference

2.2.0
gz/utils/NeverDestroyed.hh
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2021 Open Source Robotics Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17 
18 #ifndef GZ_UTILS_NEVERDESTROYED_HH_
19 #define GZ_UTILS_NEVERDESTROYED_HH_
20 
21 #include <new>
22 #include <type_traits>
23 #include <utility>
24 
25 namespace gz
26 {
27 namespace utils
28 {
116 //
117 // The above examples are repeated in the unit test; keep them in sync.
118 template <typename T>
120 {
122  public: template <typename... Args>
123  explicit NeverDestroyed(Args &&... args)
124  {
125  // Uses "placement new" to construct a `T` in `storage_`.
126  new (&this->storage) T(std::forward<Args>(args)...);
127  }
128 
130  public: ~NeverDestroyed() = default;
131 
133  public: NeverDestroyed(const NeverDestroyed &) = delete;
134 
136  public: NeverDestroyed(NeverDestroyed &&) = delete;
137 
139  public: NeverDestroyed &operator=(const NeverDestroyed &) = delete;
140 
142  public: NeverDestroyed &operator=(NeverDestroyed &&) noexcept = delete;
143 
145  public: T &Access()
146  {
147  return *reinterpret_cast<T *>(&this->storage);
148  }
149 
150  public: const T &Access() const
151  {
152  return *reinterpret_cast<const T *>(&this->storage);
153  }
154 
155  private: typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
156 };
157 } // namespace utils
158 } // namespace gz
159 
160 #endif // GZ_UTILS_NEVERDESTROYED_HH_