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>
WrapUnique(T * ptr)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 namespace memory_internal {
79 
80 // Traits to select proper overload and return type for `absl::make_unique<>`.
81 template <typename T>
82 struct MakeUniqueResult {
83   using scalar = std::unique_ptr<T>;
84 };
85 template <typename T>
86 struct MakeUniqueResult<T[]> {
87   using array = std::unique_ptr<T[]>;
88 };
89 template <typename T, size_t N>
90 struct MakeUniqueResult<T[N]> {
91   using invalid = void;
92 };
93 
94 }  // namespace memory_internal
95 
96 // gcc 4.8 has __cplusplus at 201301 but the libstdc++ shipped with it doesn't
97 // define make_unique.  Other supported compilers either just define __cplusplus
98 // as 201103 but have make_unique (msvc), or have make_unique whenever
99 // __cplusplus > 201103 (clang).
100 #if (__cplusplus > 201103L || defined(_MSC_VER)) && \
101     !(defined(__GLIBCXX__) && !defined(__cpp_lib_make_unique))
102 using std::make_unique;
103 #else
104 // -----------------------------------------------------------------------------
105 // Function Template: make_unique<T>()
106 // -----------------------------------------------------------------------------
107 //
108 // Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries
109 // during the construction process. `absl::make_unique<>` also avoids redundant
110 // type declarations, by avoiding the need to explicitly use the `new` operator.
111 //
112 // This implementation of `absl::make_unique<>` is designed for C++11 code and
113 // will be replaced in C++14 by the equivalent `std::make_unique<>` abstraction.
114 // `absl::make_unique<>` is designed to be 100% compatible with
115 // `std::make_unique<>` so that the eventual migration will involve a simple
116 // rename operation.
117 //
118 // For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic,
119 // see Herb Sutter's explanation on
120 // (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/].
121 // (In general, reviewers should treat `new T(a,b)` with scrutiny.)
122 //
123 // Example usage:
124 //
125 //    auto p = make_unique<X>(args...);  // 'p'  is a std::unique_ptr<X>
126 //    auto pa = make_unique<X[]>(5);     // 'pa' is a std::unique_ptr<X[]>
127 //
128 // Three overloads of `absl::make_unique` are required:
129 //
130 //   - For non-array T:
131 //
132 //       Allocates a T with `new T(std::forward<Args> args...)`,
133 //       forwarding all `args` to T's constructor.
134 //       Returns a `std::unique_ptr<T>` owning that object.
135 //
136 //   - For an array of unknown bounds T[]:
137 //
138 //       `absl::make_unique<>` will allocate an array T of type U[] with
139 //       `new U[n]()` and return a `std::unique_ptr<U[]>` owning that array.
140 //
141 //       Note that 'U[n]()' is different from 'U[n]', and elements will be
142 //       value-initialized. Note as well that `std::unique_ptr` will perform its
143 //       own destruction of the array elements upon leaving scope, even though
144 //       the array [] does not have a default destructor.
145 //
146 //       NOTE: an array of unknown bounds T[] may still be (and often will be)
147 //       initialized to have a size, and will still use this overload. E.g:
148 //
149 //         auto my_array = absl::make_unique<int[]>(10);
150 //
151 //   - For an array of known bounds T[N]:
152 //
153 //       `absl::make_unique<>` is deleted (like with `std::make_unique<>`) as
154 //       this overload is not useful.
155 //
156 //       NOTE: an array of known bounds T[N] is not considered a useful
157 //       construction, and may cause undefined behavior in templates. E.g:
158 //
159 //         auto my_array = absl::make_unique<int[10]>();
160 //
161 //       In those cases, of course, you can still use the overload above and
162 //       simply initialize it to its desired size:
163 //
164 //         auto my_array = absl::make_unique<int[]>(10);
165 
166 // `absl::make_unique` overload for non-array types.
167 template <typename T, typename... Args>
168 typename memory_internal::MakeUniqueResult<T>::scalar make_unique(
169     Args&&... args) {
170   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
171 }
172 
173 // `absl::make_unique` overload for an array T[] of unknown bounds.
174 // The array allocation needs to use the `new T[size]` form and cannot take
175 // element constructor arguments. The `std::unique_ptr` will manage destructing
176 // these array elements.
177 template <typename T>
178 typename memory_internal::MakeUniqueResult<T>::array make_unique(size_t n) {
179   return std::unique_ptr<T>(new typename absl::remove_extent_t<T>[n]());
180 }
181 
182 // `absl::make_unique` overload for an array T[N] of known bounds.
183 // This construction will be rejected.
184 template <typename T, typename... Args>
185 typename memory_internal::MakeUniqueResult<T>::invalid make_unique(
186     Args&&... /* args */) = delete;
187 #endif
188 
189 // -----------------------------------------------------------------------------
190 // Function Template: RawPtr()
191 // -----------------------------------------------------------------------------
192 //
193 // Extracts the raw pointer from a pointer-like value `ptr`. `absl::RawPtr` is
194 // useful within templates that need to handle a complement of raw pointers,
195 // `std::nullptr_t`, and smart pointers.
196 template <typename T>
197 auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) {
198   // ptr is a forwarding reference to support Ts with non-const operators.
199   return (ptr != nullptr) ? std::addressof(*ptr) : nullptr;
200 }
201 inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; }
202 
203 // -----------------------------------------------------------------------------
204 // Function Template: ShareUniquePtr()
205 // -----------------------------------------------------------------------------
206 //
207 // Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced
208 // type. Ownership (if any) of the held value is transferred to the returned
209 // shared pointer.
210 //
211 // Example:
212 //
213 //     auto up = absl::make_unique<int>(10);
214 //     auto sp = absl::ShareUniquePtr(std::move(up));  // shared_ptr<int>
215 //     CHECK_EQ(*sp, 10);
216 //     CHECK(up == nullptr);
217 //
218 // Note that this conversion is correct even when T is an array type, and more
219 // generally it works for *any* deleter of the `unique_ptr` (single-object
220 // deleter, array deleter, or any custom deleter), since the deleter is adopted
221 // by the shared pointer as well. The deleter is copied (unless it is a
222 // reference).
223 //
224 // Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a
225 // null shared pointer does not attempt to call the deleter.
226 template <typename T, typename D>
227 std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) {
228   return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>();
229 }
230 
231 // -----------------------------------------------------------------------------
232 // Function Template: WeakenPtr()
233 // -----------------------------------------------------------------------------
234 //
235 // Creates a weak pointer associated with a given shared pointer. The returned
236 // value is a `std::weak_ptr` of deduced type.
237 //
238 // Example:
239 //
240 //    auto sp = std::make_shared<int>(10);
241 //    auto wp = absl::WeakenPtr(sp);
242 //    CHECK_EQ(sp.get(), wp.lock().get());
243 //    sp.reset();
244 //    CHECK(wp.lock() == nullptr);
245 //
246 template <typename T>
247 std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) {
248   return std::weak_ptr<T>(ptr);
249 }
250 
251 namespace memory_internal {
252 
253 // ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D.
254 template <template <typename> class Extract, typename Obj, typename Default,
255           typename>
256 struct ExtractOr {
257   using type = Default;
258 };
259 
260 template <template <typename> class Extract, typename Obj, typename Default>
261 struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> {
262   using type = Extract<Obj>;
263 };
264 
265 template <template <typename> class Extract, typename Obj, typename Default>
266 using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type;
267 
268 // Extractors for the features of allocators.
269 template <typename T>
270 using GetPointer = typename T::pointer;
271 
272 template <typename T>
273 using GetConstPointer = typename T::const_pointer;
274 
275 template <typename T>
276 using GetVoidPointer = typename T::void_pointer;
277 
278 template <typename T>
279 using GetConstVoidPointer = typename T::const_void_pointer;
280 
281 template <typename T>
282 using GetDifferenceType = typename T::difference_type;
283 
284 template <typename T>
285 using GetSizeType = typename T::size_type;
286 
287 template <typename T>
288 using GetPropagateOnContainerCopyAssignment =
289     typename T::propagate_on_container_copy_assignment;
290 
291 template <typename T>
292 using GetPropagateOnContainerMoveAssignment =
293     typename T::propagate_on_container_move_assignment;
294 
295 template <typename T>
296 using GetPropagateOnContainerSwap = typename T::propagate_on_container_swap;
297 
298 template <typename T>
299 using GetIsAlwaysEqual = typename T::is_always_equal;
300 
301 template <typename T>
302 struct GetFirstArg;
303 
304 template <template <typename...> class Class, typename T, typename... Args>
305 struct GetFirstArg<Class<T, Args...>> {
306   using type = T;
307 };
308 
309 template <typename Ptr, typename = void>
310 struct ElementType {
311   using type = typename GetFirstArg<Ptr>::type;
312 };
313 
314 template <typename T>
315 struct ElementType<T, void_t<typename T::element_type>> {
316   using type = typename T::element_type;
317 };
318 
319 template <typename T, typename U>
320 struct RebindFirstArg;
321 
322 template <template <typename...> class Class, typename T, typename... Args,
323           typename U>
324 struct RebindFirstArg<Class<T, Args...>, U> {
325   using type = Class<U, Args...>;
326 };
327 
328 template <typename T, typename U, typename = void>
329 struct RebindPtr {
330   using type = typename RebindFirstArg<T, U>::type;
331 };
332 
333 template <typename T, typename U>
334 struct RebindPtr<T, U, void_t<typename T::template rebind<U>>> {
335   using type = typename T::template rebind<U>;
336 };
337 
338 template <typename T, typename U>
339 constexpr bool HasRebindAlloc(...) {
340   return false;
341 }
342 
343 template <typename T, typename U>
344 constexpr bool HasRebindAlloc(typename T::template rebind<U>::other*) {
345   return true;
346 }
347 
348 template <typename T, typename U, bool = HasRebindAlloc<T, U>(nullptr)>
349 struct RebindAlloc {
350   using type = typename RebindFirstArg<T, U>::type;
351 };
352 
353 template <typename T, typename U>
354 struct RebindAlloc<T, U, true> {
355   using type = typename T::template rebind<U>::other;
356 };
357 
358 }  // namespace memory_internal
359 
360 // -----------------------------------------------------------------------------
361 // Class Template: pointer_traits
362 // -----------------------------------------------------------------------------
363 //
364 // An implementation of C++11's std::pointer_traits.
365 //
366 // Provided for portability on toolchains that have a working C++11 compiler,
367 // but the standard library is lacking in C++11 support. For example, some
368 // version of the Android NDK.
369 //
370 
371 template <typename Ptr>
372 struct pointer_traits {
373   using pointer = Ptr;
374 
375   // element_type:
376   // Ptr::element_type if present. Otherwise T if Ptr is a template
377   // instantiation Template<T, Args...>
378   using element_type = typename memory_internal::ElementType<Ptr>::type;
379 
380   // difference_type:
381   // Ptr::difference_type if present, otherwise std::ptrdiff_t
382   using difference_type =
383       memory_internal::ExtractOrT<memory_internal::GetDifferenceType, Ptr,
384                                   std::ptrdiff_t>;
385 
386   // rebind:
387   // Ptr::rebind<U> if exists, otherwise Template<U, Args...> if Ptr is a
388   // template instantiation Template<T, Args...>
389   template <typename U>
390   using rebind = typename memory_internal::RebindPtr<Ptr, U>::type;
391 
392   // pointer_to:
393   // Calls Ptr::pointer_to(r)
394   static pointer pointer_to(element_type& r) {  // NOLINT(runtime/references)
395     return Ptr::pointer_to(r);
396   }
397 };
398 
399 // Specialization for T*.
400 template <typename T>
401 struct pointer_traits<T*> {
402   using pointer = T*;
403   using element_type = T;
404   using difference_type = std::ptrdiff_t;
405 
406   template <typename U>
407   using rebind = U*;
408 
409   // pointer_to:
410   // Calls std::addressof(r)
411   static pointer pointer_to(
412       element_type& r) noexcept {  // NOLINT(runtime/references)
413     return std::addressof(r);
414   }
415 };
416 
417 // -----------------------------------------------------------------------------
418 // Class Template: allocator_traits
419 // -----------------------------------------------------------------------------
420 //
421 // A C++11 compatible implementation of C++17's std::allocator_traits.
422 //
423 template <typename Alloc>
424 struct allocator_traits {
425   using allocator_type = Alloc;
426 
427   // value_type:
428   // Alloc::value_type
429   using value_type = typename Alloc::value_type;
430 
431   // pointer:
432   // Alloc::pointer if present, otherwise value_type*
433   using pointer = memory_internal::ExtractOrT<memory_internal::GetPointer,
434                                               Alloc, value_type*>;
435 
436   // const_pointer:
437   // Alloc::const_pointer if present, otherwise
438   // absl::pointer_traits<pointer>::rebind<const value_type>
439   using const_pointer =
440       memory_internal::ExtractOrT<memory_internal::GetConstPointer, Alloc,
441                                   typename absl::pointer_traits<pointer>::
442                                       template rebind<const value_type>>;
443 
444   // void_pointer:
445   // Alloc::void_pointer if present, otherwise
446   // absl::pointer_traits<pointer>::rebind<void>
447   using void_pointer = memory_internal::ExtractOrT<
448       memory_internal::GetVoidPointer, Alloc,
449       typename absl::pointer_traits<pointer>::template rebind<void>>;
450 
451   // const_void_pointer:
452   // Alloc::const_void_pointer if present, otherwise
453   // absl::pointer_traits<pointer>::rebind<const void>
454   using const_void_pointer = memory_internal::ExtractOrT<
455       memory_internal::GetConstVoidPointer, Alloc,
456       typename absl::pointer_traits<pointer>::template rebind<const void>>;
457 
458   // difference_type:
459   // Alloc::difference_type if present, otherwise
460   // absl::pointer_traits<pointer>::difference_type
461   using difference_type = memory_internal::ExtractOrT<
462       memory_internal::GetDifferenceType, Alloc,
463       typename absl::pointer_traits<pointer>::difference_type>;
464 
465   // size_type:
466   // Alloc::size_type if present, otherwise
467   // std::make_unsigned<difference_type>::type
468   using size_type = memory_internal::ExtractOrT<
469       memory_internal::GetSizeType, Alloc,
470       typename std::make_unsigned<difference_type>::type>;
471 
472   // propagate_on_container_copy_assignment:
473   // Alloc::propagate_on_container_copy_assignment if present, otherwise
474   // std::false_type
475   using propagate_on_container_copy_assignment = memory_internal::ExtractOrT<
476       memory_internal::GetPropagateOnContainerCopyAssignment, Alloc,
477       std::false_type>;
478 
479   // propagate_on_container_move_assignment:
480   // Alloc::propagate_on_container_move_assignment if present, otherwise
481   // std::false_type
482   using propagate_on_container_move_assignment = memory_internal::ExtractOrT<
483       memory_internal::GetPropagateOnContainerMoveAssignment, Alloc,
484       std::false_type>;
485 
486   // propagate_on_container_swap:
487   // Alloc::propagate_on_container_swap if present, otherwise std::false_type
488   using propagate_on_container_swap =
489       memory_internal::ExtractOrT<memory_internal::GetPropagateOnContainerSwap,
490                                   Alloc, std::false_type>;
491 
492   // is_always_equal:
493   // Alloc::is_always_equal if present, otherwise std::is_empty<Alloc>::type
494   using is_always_equal =
495       memory_internal::ExtractOrT<memory_internal::GetIsAlwaysEqual, Alloc,
496                                   typename std::is_empty<Alloc>::type>;
497 
498   // rebind_alloc:
499   // Alloc::rebind<T>::other if present, otherwise Alloc<T, Args> if this Alloc
500   // is Alloc<U, Args>
501   template <typename T>
502   using rebind_alloc = typename memory_internal::RebindAlloc<Alloc, T>::type;
503 
504   // rebind_traits:
505   // absl::allocator_traits<rebind_alloc<T>>
506   template <typename T>
507   using rebind_traits = absl::allocator_traits<rebind_alloc<T>>;
508 
509   // allocate(Alloc& a, size_type n):
510   // Calls a.allocate(n)
511   static pointer allocate(Alloc& a,  // NOLINT(runtime/references)
512                           size_type n) {
513     return a.allocate(n);
514   }
515 
516   // allocate(Alloc& a, size_type n, const_void_pointer hint):
517   // Calls a.allocate(n, hint) if possible.
518   // If not possible, calls a.allocate(n)
519   static pointer allocate(Alloc& a, size_type n,  // NOLINT(runtime/references)
520                           const_void_pointer hint) {
521     return allocate_impl(0, a, n, hint);
522   }
523 
524   // deallocate(Alloc& a, pointer p, size_type n):
525   // Calls a.deallocate(p, n)
526   static void deallocate(Alloc& a, pointer p,  // NOLINT(runtime/references)
527                          size_type n) {
528     a.deallocate(p, n);
529   }
530 
531   // construct(Alloc& a, T* p, Args&&... args):
532   // Calls a.construct(p, std::forward<Args>(args)...) if possible.
533   // If not possible, calls
534   //   ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)
535   template <typename T, typename... Args>
536   static void construct(Alloc& a, T* p,  // NOLINT(runtime/references)
537                         Args&&... args) {
538     construct_impl(0, a, p, std::forward<Args>(args)...);
539   }
540 
541   // destroy(Alloc& a, T* p):
542   // Calls a.destroy(p) if possible. If not possible, calls p->~T().
543   template <typename T>
544   static void destroy(Alloc& a, T* p) {  // NOLINT(runtime/references)
545     destroy_impl(0, a, p);
546   }
547 
548   // max_size(const Alloc& a):
549   // Returns a.max_size() if possible. If not possible, returns
550   //   std::numeric_limits<size_type>::max() / sizeof(value_type)
551   static size_type max_size(const Alloc& a) { return max_size_impl(0, a); }
552 
553   // select_on_container_copy_construction(const Alloc& a):
554   // Returns a.select_on_container_copy_construction() if possible.
555   // If not possible, returns a.
556   static Alloc select_on_container_copy_construction(const Alloc& a) {
557     return select_on_container_copy_construction_impl(0, a);
558   }
559 
560  private:
561   template <typename A>
562   static auto allocate_impl(int, A& a,  // NOLINT(runtime/references)
563                             size_type n, const_void_pointer hint)
564       -> decltype(a.allocate(n, hint)) {
565     return a.allocate(n, hint);
566   }
567   static pointer allocate_impl(char, Alloc& a,  // NOLINT(runtime/references)
568                                size_type n, const_void_pointer) {
569     return a.allocate(n);
570   }
571 
572   template <typename A, typename... Args>
573   static auto construct_impl(int, A& a,  // NOLINT(runtime/references)
574                              Args&&... args)
575       -> decltype(a.construct(std::forward<Args>(args)...)) {
576     a.construct(std::forward<Args>(args)...);
577   }
578 
579   template <typename T, typename... Args>
580   static void construct_impl(char, Alloc&, T* p, Args&&... args) {
581     ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
582   }
583 
584   template <typename A, typename T>
585   static auto destroy_impl(int, A& a,  // NOLINT(runtime/references)
586                            T* p) -> decltype(a.destroy(p)) {
587     a.destroy(p);
588   }
589   template <typename T>
590   static void destroy_impl(char, Alloc&, T* p) {
591     p->~T();
592   }
593 
594   template <typename A>
595   static auto max_size_impl(int, const A& a) -> decltype(a.max_size()) {
596     return a.max_size();
597   }
598   static size_type max_size_impl(char, const Alloc&) {
599     return (std::numeric_limits<size_type>::max)() / sizeof(value_type);
600   }
601 
602   template <typename A>
603   static auto select_on_container_copy_construction_impl(int, const A& a)
604       -> decltype(a.select_on_container_copy_construction()) {
605     return a.select_on_container_copy_construction();
606   }
607   static Alloc select_on_container_copy_construction_impl(char,
608                                                           const Alloc& a) {
609     return a;
610   }
611 };
612 
613 namespace memory_internal {
614 
615 // This template alias transforms Alloc::is_nothrow into a metafunction with
616 // Alloc as a parameter so it can be used with ExtractOrT<>.
617 template <typename Alloc>
618 using GetIsNothrow = typename Alloc::is_nothrow;
619 
620 }  // namespace memory_internal
621 
622 // ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to
623 // specify whether the default allocation function can throw or never throws.
624 // If the allocation function never throws, user should define it to a non-zero
625 // value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`).
626 // If the allocation function can throw, user should leave it undefined or
627 // define it to zero.
628 //
629 // allocator_is_nothrow<Alloc> is a traits class that derives from
630 // Alloc::is_nothrow if present, otherwise std::false_type. It's specialized
631 // for Alloc = std::allocator<T> for any type T according to the state of
632 // ABSL_ALLOCATOR_NOTHROW.
633 //
634 // default_allocator_is_nothrow is a class that derives from std::true_type
635 // when the default allocator (global operator new) never throws, and
636 // std::false_type when it can throw. It is a convenience shorthand for writing
637 // allocator_is_nothrow<std::allocator<T>> (T can be any type).
638 // NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from
639 // the same type for all T, because users should specialize neither
640 // allocator_is_nothrow nor std::allocator.
641 template <typename Alloc>
642 struct allocator_is_nothrow
643     : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc,
644                                   std::false_type> {};
645 
646 #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW
647 template <typename T>
648 struct allocator_is_nothrow<std::allocator<T>> : std::true_type {};
649 struct default_allocator_is_nothrow : std::true_type {};
650 #else
651 struct default_allocator_is_nothrow : std::false_type {};
652 #endif
653 
654 namespace memory_internal {
655 template <typename Allocator, typename Iterator, typename... Args>
656 void ConstructRange(Allocator& alloc, Iterator first, Iterator last,
657                     const Args&... args) {
658   for (Iterator cur = first; cur != last; ++cur) {
659     ABSL_INTERNAL_TRY {
660       std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
661                                                   args...);
662     }
663     ABSL_INTERNAL_CATCH_ANY {
664       while (cur != first) {
665         --cur;
666         std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
667       }
668       ABSL_INTERNAL_RETHROW;
669     }
670   }
671 }
672 
673 template <typename Allocator, typename Iterator, typename InputIterator>
674 void CopyRange(Allocator& alloc, Iterator destination, InputIterator first,
675                InputIterator last) {
676   for (Iterator cur = destination; first != last;
677        static_cast<void>(++cur), static_cast<void>(++first)) {
678     ABSL_INTERNAL_TRY {
679       std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
680                                                   *first);
681     }
682     ABSL_INTERNAL_CATCH_ANY {
683       while (cur != destination) {
684         --cur;
685         std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
686       }
687       ABSL_INTERNAL_RETHROW;
688     }
689   }
690 }
691 }  // namespace memory_internal
692 ABSL_NAMESPACE_END
693 }  // namespace absl
694 
695 #endif  // ABSL_MEMORY_MEMORY_H_
696