/src/abseil-cpp/absl/memory/memory.h
Line | Count | Source |
1 | | // Copyright 2017 The Abseil Authors. |
2 | | // |
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 | | // https://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 | | // File: memory.h |
17 | | // ----------------------------------------------------------------------------- |
18 | | // |
19 | | // This header file contains utility functions for managing the creation and |
20 | | // conversion of smart pointers. This file is an extension to the C++ |
21 | | // standard <memory> library header file. |
22 | | |
23 | | #ifndef ABSL_MEMORY_MEMORY_H_ |
24 | | #define ABSL_MEMORY_MEMORY_H_ |
25 | | |
26 | | #include <cstddef> |
27 | | #include <limits> |
28 | | #include <memory> |
29 | | #include <new> |
30 | | #include <type_traits> |
31 | | #include <utility> |
32 | | |
33 | | #include "absl/base/macros.h" |
34 | | #include "absl/meta/type_traits.h" |
35 | | |
36 | | namespace absl { |
37 | | ABSL_NAMESPACE_BEGIN |
38 | | |
39 | | // ----------------------------------------------------------------------------- |
40 | | // Function Template: WrapUnique() |
41 | | // ----------------------------------------------------------------------------- |
42 | | // |
43 | | // Adopts ownership from a raw pointer and transfers it to the returned |
44 | | // `std::unique_ptr`, whose type is deduced. Because of this deduction, *do not* |
45 | | // specify the template type `T` when calling `WrapUnique`. |
46 | | // |
47 | | // Example: |
48 | | // X* NewX(int, int); |
49 | | // auto x = WrapUnique(NewX(1, 2)); // 'x' is std::unique_ptr<X>. |
50 | | // |
51 | | // Do not call WrapUnique with an explicit type, as in |
52 | | // `WrapUnique<X>(NewX(1, 2))`. The purpose of WrapUnique is to automatically |
53 | | // deduce the pointer type. If you wish to make the type explicit, just use |
54 | | // `std::unique_ptr` directly. |
55 | | // |
56 | | // auto x = std::unique_ptr<X>(NewX(1, 2)); |
57 | | // - or - |
58 | | // std::unique_ptr<X> x(NewX(1, 2)); |
59 | | // |
60 | | // While `absl::WrapUnique` is useful for capturing the output of a raw |
61 | | // pointer factory, prefer 'absl::make_unique<T>(args...)' over |
62 | | // 'absl::WrapUnique(new T(args...))'. |
63 | | // |
64 | | // auto x = WrapUnique(new X(1, 2)); // works, but nonideal. |
65 | | // auto x = make_unique<X>(1, 2); // safer, standard, avoids raw 'new'. |
66 | | // |
67 | | // Note that `absl::WrapUnique(p)` is valid only if `delete p` is a valid |
68 | | // expression. In particular, `absl::WrapUnique()` cannot wrap pointers to |
69 | | // arrays, functions or void, and it must not be used to capture pointers |
70 | | // obtained from array-new expressions (even though that would compile!). |
71 | | template <typename T> |
72 | | std::unique_ptr<T> WrapUnique(T* ptr) { |
73 | | static_assert(!std::is_array<T>::value, "array types are unsupported"); |
74 | | static_assert(std::is_object<T>::value, "non-object types are unsupported"); |
75 | | return std::unique_ptr<T>(ptr); |
76 | | } |
77 | | |
78 | | // ----------------------------------------------------------------------------- |
79 | | // Function Template: make_unique<T>() |
80 | | // ----------------------------------------------------------------------------- |
81 | | // |
82 | | // Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries |
83 | | // during the construction process. `absl::make_unique<>` also avoids redundant |
84 | | // type declarations, by avoiding the need to explicitly use the `new` operator. |
85 | | // |
86 | | // https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique |
87 | | // |
88 | | // For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic, |
89 | | // see Herb Sutter's explanation on |
90 | | // (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/]. |
91 | | // (In general, reviewers should treat `new T(a,b)` with scrutiny.) |
92 | | // |
93 | | // Historical note: Abseil once provided a C++11 compatible implementation of |
94 | | // the C++14's `std::make_unique`. Now that C++11 support has been sunsetted, |
95 | | // `absl::make_unique` simply uses the STL-provided implementation. New code |
96 | | // should use `std::make_unique`. |
97 | | using std::make_unique; |
98 | | |
99 | | namespace memory_internal { |
100 | | |
101 | | // Traits to select proper overload and return type for |
102 | | // `absl::make_unique_for_overwrite<>`. |
103 | | template <typename T> |
104 | | struct MakeUniqueResult { |
105 | | using scalar = std::unique_ptr<T>; |
106 | | }; |
107 | | template <typename T> |
108 | | struct MakeUniqueResult<T[]> { |
109 | | using array = std::unique_ptr<T[]>; |
110 | | }; |
111 | | template <typename T, size_t N> |
112 | | struct MakeUniqueResult<T[N]> { |
113 | | using invalid = void; |
114 | | }; |
115 | | |
116 | | } // namespace memory_internal |
117 | | |
118 | | // These are make_unique_for_overwrite variants modeled after |
119 | | // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1973r1.pdf |
120 | | // Unlike absl::make_unique, values are default initialized rather than value |
121 | | // initialized. |
122 | | // |
123 | | // `absl::make_unique_for_overwrite` overload for non-array types. |
124 | | template <typename T> |
125 | | typename memory_internal::MakeUniqueResult<T>::scalar |
126 | | make_unique_for_overwrite() { |
127 | | return std::unique_ptr<T>(new T); |
128 | | } |
129 | | |
130 | | // `absl::make_unique_for_overwrite` overload for an array T[] of unknown |
131 | | // bounds. The array allocation needs to use the `new T[size]` form and cannot |
132 | | // take element constructor arguments. The `std::unique_ptr` will manage |
133 | | // destructing these array elements. |
134 | | template <typename T> |
135 | | typename memory_internal::MakeUniqueResult<T>::array |
136 | | make_unique_for_overwrite(size_t n) { |
137 | | return std::unique_ptr<T>(new typename absl::remove_extent_t<T>[n]); |
138 | | } |
139 | | |
140 | | // `absl::make_unique_for_overwrite` overload for an array T[N] of known bounds. |
141 | | // This construction will be rejected. |
142 | | template <typename T, typename... Args> |
143 | | typename memory_internal::MakeUniqueResult<T>::invalid |
144 | | make_unique_for_overwrite(Args&&... /* args */) = delete; |
145 | | |
146 | | // ----------------------------------------------------------------------------- |
147 | | // Function Template: RawPtr() |
148 | | // ----------------------------------------------------------------------------- |
149 | | // |
150 | | // Extracts the raw pointer from a pointer-like value `ptr`. `absl::RawPtr` is |
151 | | // useful within templates that need to handle a complement of raw pointers, |
152 | | // `std::nullptr_t`, and smart pointers. |
153 | | template <typename T> |
154 | | auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) { |
155 | | // ptr is a forwarding reference to support Ts with non-const operators. |
156 | | return (ptr != nullptr) ? std::addressof(*ptr) : nullptr; |
157 | | } |
158 | 0 | inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; } |
159 | | |
160 | | // ----------------------------------------------------------------------------- |
161 | | // Function Template: ShareUniquePtr() |
162 | | // ----------------------------------------------------------------------------- |
163 | | // |
164 | | // Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced |
165 | | // type. Ownership (if any) of the held value is transferred to the returned |
166 | | // shared pointer. |
167 | | // |
168 | | // Example: |
169 | | // |
170 | | // auto up = absl::make_unique<int>(10); |
171 | | // auto sp = absl::ShareUniquePtr(std::move(up)); // shared_ptr<int> |
172 | | // CHECK_EQ(*sp, 10); |
173 | | // CHECK(up == nullptr); |
174 | | // |
175 | | // Note that this conversion is correct even when T is an array type, and more |
176 | | // generally it works for *any* deleter of the `unique_ptr` (single-object |
177 | | // deleter, array deleter, or any custom deleter), since the deleter is adopted |
178 | | // by the shared pointer as well. The deleter is copied (unless it is a |
179 | | // reference). |
180 | | // |
181 | | // Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a |
182 | | // null shared pointer does not attempt to call the deleter. |
183 | | template <typename T, typename D> |
184 | | std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) { |
185 | | return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>(); |
186 | | } |
187 | | |
188 | | // ----------------------------------------------------------------------------- |
189 | | // Function Template: WeakenPtr() |
190 | | // ----------------------------------------------------------------------------- |
191 | | // |
192 | | // Creates a weak pointer associated with a given shared pointer. The returned |
193 | | // value is a `std::weak_ptr` of deduced type. |
194 | | // |
195 | | // Example: |
196 | | // |
197 | | // auto sp = std::make_shared<int>(10); |
198 | | // auto wp = absl::WeakenPtr(sp); |
199 | | // CHECK_EQ(sp.get(), wp.lock().get()); |
200 | | // sp.reset(); |
201 | | // CHECK(wp.lock() == nullptr); |
202 | | // |
203 | | template <typename T> |
204 | | std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) { |
205 | | return std::weak_ptr<T>(ptr); |
206 | | } |
207 | | |
208 | | // ----------------------------------------------------------------------------- |
209 | | // Class Template: pointer_traits |
210 | | // ----------------------------------------------------------------------------- |
211 | | // |
212 | | // Historical note: Abseil once provided an implementation of |
213 | | // `std::pointer_traits` for platforms that had not yet provided it. Those |
214 | | // platforms are no longer supported. New code should simply use |
215 | | // `std::pointer_traits`. |
216 | | using std::pointer_traits; |
217 | | |
218 | | // ----------------------------------------------------------------------------- |
219 | | // Class Template: allocator_traits |
220 | | // ----------------------------------------------------------------------------- |
221 | | // |
222 | | // Historical note: Abseil once provided an implementation of |
223 | | // `std::allocator_traits` for platforms that had not yet provided it. Those |
224 | | // platforms are no longer supported. New code should simply use |
225 | | // `std::allocator_traits`. |
226 | | using std::allocator_traits; |
227 | | |
228 | | namespace memory_internal { |
229 | | |
230 | | // ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D. |
231 | | template <template <typename> class Extract, typename Obj, typename Default, |
232 | | typename> |
233 | | struct ExtractOr { |
234 | | using type = Default; |
235 | | }; |
236 | | |
237 | | template <template <typename> class Extract, typename Obj, typename Default> |
238 | | struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> { |
239 | | using type = Extract<Obj>; |
240 | | }; |
241 | | |
242 | | template <template <typename> class Extract, typename Obj, typename Default> |
243 | | using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type; |
244 | | |
245 | | // This template alias transforms Alloc::is_nothrow into a metafunction with |
246 | | // Alloc as a parameter so it can be used with ExtractOrT<>. |
247 | | template <typename Alloc> |
248 | | using GetIsNothrow = typename Alloc::is_nothrow; |
249 | | |
250 | | } // namespace memory_internal |
251 | | |
252 | | // ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to |
253 | | // specify whether the default allocation function can throw or never throws. |
254 | | // If the allocation function never throws, user should define it to a non-zero |
255 | | // value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`). |
256 | | // If the allocation function can throw, user should leave it undefined or |
257 | | // define it to zero. |
258 | | // |
259 | | // allocator_is_nothrow<Alloc> is a traits class that derives from |
260 | | // Alloc::is_nothrow if present, otherwise std::false_type. It's specialized |
261 | | // for Alloc = std::allocator<T> for any type T according to the state of |
262 | | // ABSL_ALLOCATOR_NOTHROW. |
263 | | // |
264 | | // default_allocator_is_nothrow is a class that derives from std::true_type |
265 | | // when the default allocator (global operator new) never throws, and |
266 | | // std::false_type when it can throw. It is a convenience shorthand for writing |
267 | | // allocator_is_nothrow<std::allocator<T>> (T can be any type). |
268 | | // NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from |
269 | | // the same type for all T, because users should specialize neither |
270 | | // allocator_is_nothrow nor std::allocator. |
271 | | template <typename Alloc> |
272 | | struct allocator_is_nothrow |
273 | | : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc, |
274 | | std::false_type> {}; |
275 | | |
276 | | #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW |
277 | | template <typename T> |
278 | | struct allocator_is_nothrow<std::allocator<T>> : std::true_type {}; |
279 | | struct default_allocator_is_nothrow : std::true_type {}; |
280 | | #else |
281 | | struct default_allocator_is_nothrow : std::false_type {}; |
282 | | #endif |
283 | | |
284 | | namespace memory_internal { |
285 | | template <typename Allocator, typename Iterator, typename... Args> |
286 | | void ConstructRange(Allocator& alloc, Iterator first, Iterator last, |
287 | 0 | const Args&... args) { |
288 | 0 | for (Iterator cur = first; cur != last; ++cur) { |
289 | 0 | ABSL_INTERNAL_TRY { |
290 | 0 | std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur), |
291 | 0 | args...); |
292 | 0 | } |
293 | 0 | ABSL_INTERNAL_CATCH_ANY { |
294 | 0 | while (cur != first) { |
295 | 0 | --cur; |
296 | 0 | std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur)); |
297 | 0 | } |
298 | 0 | ABSL_INTERNAL_RETHROW; |
299 | 0 | } |
300 | 0 | } |
301 | 0 | } |
302 | | |
303 | | template <typename Allocator, typename Iterator, typename InputIterator> |
304 | | void CopyRange(Allocator& alloc, Iterator destination, InputIterator first, |
305 | | InputIterator last) { |
306 | | for (Iterator cur = destination; first != last; |
307 | | static_cast<void>(++cur), static_cast<void>(++first)) { |
308 | | ABSL_INTERNAL_TRY { |
309 | | std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur), |
310 | | *first); |
311 | | } |
312 | | ABSL_INTERNAL_CATCH_ANY { |
313 | | while (cur != destination) { |
314 | | --cur; |
315 | | std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur)); |
316 | | } |
317 | | ABSL_INTERNAL_RETHROW; |
318 | | } |
319 | | } |
320 | | } |
321 | | } // namespace memory_internal |
322 | | ABSL_NAMESPACE_END |
323 | | } // namespace absl |
324 | | |
325 | | #endif // ABSL_MEMORY_MEMORY_H_ |