Coverage Report

Created: 2026-07-16 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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 'std::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_v<T>, "array types are unsupported");
74
  static_assert(std::is_object_v<T>, "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 ABSL_REFACTOR_INLINE;
98
99
#if defined(__cpp_lib_smart_ptr_for_overwrite) && \
100
    __cpp_lib_smart_ptr_for_overwrite >= 202002L
101
using std::make_unique_for_overwrite;
102
#else
103
104
namespace memory_internal {
105
106
// Traits to select proper overload and return type for
107
// `absl::make_unique_for_overwrite<>`.
108
template <typename T>
109
struct MakeUniqueResult {
110
  using scalar = std::unique_ptr<T>;
111
};
112
template <typename T>
113
struct MakeUniqueResult<T[]> {
114
  using array = std::unique_ptr<T[]>;
115
};
116
template <typename T, size_t N>
117
struct MakeUniqueResult<T[N]> {
118
  using invalid = void;
119
};
120
121
}  // namespace memory_internal
122
123
// These are make_unique_for_overwrite variants modeled after
124
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1973r1.pdf
125
// Unlike std::make_unique, values are default initialized rather than value
126
// initialized.
127
//
128
// `absl::make_unique_for_overwrite` overload for non-array types.
129
template <typename T>
130
typename memory_internal::MakeUniqueResult<T>::scalar
131
make_unique_for_overwrite() {
132
  return std::unique_ptr<T>(new T);
133
}
134
135
// `absl::make_unique_for_overwrite` overload for an array T[] of unknown
136
// bounds. The array allocation needs to use the `new T[size]` form and cannot
137
// take element constructor arguments. The `std::unique_ptr` will manage
138
// destructing these array elements.
139
template <typename T>
140
typename memory_internal::MakeUniqueResult<T>::array make_unique_for_overwrite(
141
    size_t n) {
142
  return std::unique_ptr<T>(new typename std::remove_extent_t<T>[n]);
143
}
144
145
// `absl::make_unique_for_overwrite` overload for an array T[N] of known bounds.
146
// This construction will be rejected.
147
template <typename T, typename... Args>
148
typename memory_internal::MakeUniqueResult<T>::invalid
149
make_unique_for_overwrite(Args&&... /* args */) = delete;
150
151
#endif  // __cpp_lib_smart_ptr_for_overwrite
152
153
// -----------------------------------------------------------------------------
154
// Function Template: RawPtr()
155
// -----------------------------------------------------------------------------
156
//
157
// Extracts the raw pointer from a pointer-like value `ptr`. `absl::RawPtr` is
158
// useful within templates that need to handle a complement of raw pointers,
159
// `std::nullptr_t`, and smart pointers.
160
template <typename T>
161
auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) {
162
  // ptr is a forwarding reference to support Ts with non-const operators.
163
  return (ptr != nullptr) ? std::addressof(*ptr) : nullptr;
164
}
165
0
inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; }
166
167
// -----------------------------------------------------------------------------
168
// Function Template: ShareUniquePtr()
169
// -----------------------------------------------------------------------------
170
//
171
// Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced
172
// type. Ownership (if any) of the held value is transferred to the returned
173
// shared pointer.
174
//
175
// Example:
176
//
177
//     auto up = std::make_unique<int>(10);
178
//     auto sp = absl::ShareUniquePtr(std::move(up));  // shared_ptr<int>
179
//     CHECK_EQ(*sp, 10);
180
//     CHECK(up == nullptr);
181
//
182
// Note that this conversion is correct even when T is an array type, and more
183
// generally it works for *any* deleter of the `unique_ptr` (single-object
184
// deleter, array deleter, or any custom deleter), since the deleter is adopted
185
// by the shared pointer as well. The deleter is copied (unless it is a
186
// reference).
187
//
188
// Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a
189
// null shared pointer does not attempt to call the deleter.
190
template <typename T, typename D>
191
std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) {
192
  return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>();
193
}
194
195
// -----------------------------------------------------------------------------
196
// Function Template: WeakenPtr()
197
// -----------------------------------------------------------------------------
198
//
199
// Creates a weak pointer associated with a given shared pointer. The returned
200
// value is a `std::weak_ptr` of deduced type.
201
//
202
// Example:
203
//
204
//    auto sp = std::make_shared<int>(10);
205
//    auto wp = absl::WeakenPtr(sp);
206
//    CHECK_EQ(sp.get(), wp.lock().get());
207
//    sp.reset();
208
//    CHECK(wp.lock() == nullptr);
209
//
210
template <typename T>
211
std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) {
212
  return std::weak_ptr<T>(ptr);
213
}
214
215
// -----------------------------------------------------------------------------
216
// Class Template: pointer_traits
217
// -----------------------------------------------------------------------------
218
//
219
// Historical note: Abseil once provided an implementation of
220
// `std::pointer_traits` for platforms that had not yet provided it. Those
221
// platforms are no longer supported. New code should simply use
222
// `std::pointer_traits`.
223
template <typename Ptr>
224
using pointer_traits ABSL_DEPRECATE_AND_INLINE() = std::pointer_traits<Ptr>;
225
226
// -----------------------------------------------------------------------------
227
// Class Template: allocator_traits
228
// -----------------------------------------------------------------------------
229
//
230
// Historical note: Abseil once provided an implementation of
231
// `std::allocator_traits` for platforms that had not yet provided it. Those
232
// platforms are no longer supported. New code should simply use
233
// `std::allocator_traits`.
234
template <typename Alloc>
235
using allocator_traits ABSL_DEPRECATE_AND_INLINE() =
236
    std::allocator_traits<Alloc>;
237
238
namespace memory_internal {
239
240
// ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D.
241
template <template <typename> class Extract, typename Obj, typename Default,
242
          typename>
243
struct ExtractOr {
244
  using type = Default;
245
};
246
247
template <template <typename> class Extract, typename Obj, typename Default>
248
struct ExtractOr<Extract, Obj, Default, std::void_t<Extract<Obj>>> {
249
  using type = Extract<Obj>;
250
};
251
252
template <template <typename> class Extract, typename Obj, typename Default>
253
using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type;
254
255
// This template alias transforms Alloc::is_nothrow into a metafunction with
256
// Alloc as a parameter so it can be used with ExtractOrT<>.
257
template <typename Alloc>
258
using GetIsNothrow = typename Alloc::is_nothrow;
259
260
}  // namespace memory_internal
261
262
// ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to
263
// specify whether the default allocation function can throw or never throws.
264
// If the allocation function never throws, user should define it to a non-zero
265
// value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`).
266
// If the allocation function can throw, user should leave it undefined or
267
// define it to zero.
268
//
269
// allocator_is_nothrow<Alloc> is a traits class that derives from
270
// Alloc::is_nothrow if present, otherwise std::false_type. It's specialized
271
// for Alloc = std::allocator<T> for any type T according to the state of
272
// ABSL_ALLOCATOR_NOTHROW.
273
//
274
// default_allocator_is_nothrow is a class that derives from std::true_type
275
// when the default allocator (global operator new) never throws, and
276
// std::false_type when it can throw. It is a convenience shorthand for writing
277
// allocator_is_nothrow<std::allocator<T>> (T can be any type).
278
// NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from
279
// the same type for all T, because users should specialize neither
280
// allocator_is_nothrow nor std::allocator.
281
template <typename Alloc>
282
struct allocator_is_nothrow
283
    : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc,
284
                                  std::false_type> {};
285
286
#if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW
287
template <typename T>
288
struct allocator_is_nothrow<std::allocator<T>> : std::true_type {};
289
struct default_allocator_is_nothrow : std::true_type {};
290
#else
291
struct default_allocator_is_nothrow : std::false_type {};
292
#endif
293
294
namespace memory_internal {
295
template <typename Allocator, typename Iterator, typename... Args>
296
void ConstructRange(Allocator& alloc, Iterator first, Iterator last,
297
0
                    const Args&... args) {
298
0
  for (Iterator cur = first; cur != last; ++cur) {
299
0
    ABSL_INTERNAL_TRY {
300
0
      std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
301
0
                                                  args...);
302
0
    }
303
0
    ABSL_INTERNAL_CATCH_ANY {
304
0
      while (cur != first) {
305
0
        --cur;
306
0
        std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
307
0
      }
308
0
      ABSL_INTERNAL_RETHROW;
309
0
    }
310
0
  }
311
0
}
312
313
template <typename Allocator, typename Iterator, typename InputIterator>
314
void CopyRange(Allocator& alloc, Iterator destination, InputIterator first,
315
               InputIterator last) {
316
  for (Iterator cur = destination; first != last;
317
       static_cast<void>(++cur), static_cast<void>(++first)) {
318
    ABSL_INTERNAL_TRY {
319
      std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
320
                                                  *first);
321
    }
322
    ABSL_INTERNAL_CATCH_ANY {
323
      while (cur != destination) {
324
        --cur;
325
        std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
326
      }
327
      ABSL_INTERNAL_RETHROW;
328
    }
329
  }
330
}
331
}  // namespace memory_internal
332
ABSL_NAMESPACE_END
333
}  // namespace absl
334
335
#endif  // ABSL_MEMORY_MEMORY_H_