Gazebo Utils

API Reference

1.5.1
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 #include <gz/utils/config.hh>
26 
27 namespace ignition
28 {
29 namespace utils
30 {
118 //
119 // The above examples are repeated in the unit test; keep them in sync.
120 template <typename T>
122 {
124  public: template <typename... Args>
125  explicit NeverDestroyed(Args &&... args)
126  {
127  // Uses "placement new" to construct a `T` in `storage_`.
128  new (&this->storage) T(std::forward<Args>(args)...);
129  }
130 
132  public: ~NeverDestroyed() = default;
133 
135  public: NeverDestroyed(const NeverDestroyed &) = delete;
136 
138  public: NeverDestroyed(NeverDestroyed &&) = delete;
139 
141  public: NeverDestroyed &operator=(const NeverDestroyed &) = delete;
142 
144  public: NeverDestroyed &operator=(NeverDestroyed &&) noexcept = delete;
145 
147  public: T &Access()
148  {
149  return *reinterpret_cast<T *>(&this->storage);
150  }
151 
152  public: const T &Access() const
153  {
154  return *reinterpret_cast<const T *>(&this->storage);
155  }
156 
157  private: typename std::aligned_storage<sizeof(T), alignof(T)>::type storage;
158 };
159 } // namespace utils
160 } // namespace ignition
161 
162 #endif // GZ_UTILS_NEVERDESTROYED_HH_
NeverDestroyed & operator=(const NeverDestroyed &)=delete
Deleted copy assignment constructor.
Definition: gz/utils/Environment.hh:26
~NeverDestroyed()=default
Does nothing. Guaranteed!
NeverDestroyed(Args &&... args)
Passes the constructor arguments along to T using perfect forwarding.
Definition: gz/utils/NeverDestroyed.hh:125
Definition: gz/utils/NeverDestroyed.hh:121
T & Access()
Returns the underlying T reference.
Definition: gz/utils/NeverDestroyed.hh:147
const T & Access() const
Definition: gz/utils/NeverDestroyed.hh:152