Coverage Report

Created: 2026-09-14 06:45

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