libstdc++
out_ptr.h
Go to the documentation of this file.
1// Smart pointer adaptors -*- C++ -*-
2
3// Copyright The GNU Toolchain Authors.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/bits/out_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _GLIBCXX_OUT_PTR_H
31#define _GLIBCXX_OUT_PTR_H 1
32
33#pragma GCC system_header
34
35#include <bits/version.h>
36
37#ifdef __glibcxx_out_ptr // C++ >= 23
38
39#include <tuple>
40#include <bits/ptr_traits.h>
41
42namespace std _GLIBCXX_VISIBILITY(default)
43{
44_GLIBCXX_BEGIN_NAMESPACE_VERSION
45
46 /// Smart pointer adaptor for functions taking an output pointer parameter.
47 /**
48 * @tparam _Smart The type of pointer to adapt.
49 * @tparam _Pointer The type of pointer to convert to.
50 * @tparam _Args... Argument types used when resetting the smart pointer.
51 * @since C++23
52 * @headerfile <memory>
53 */
54 template<typename _Smart, typename _Pointer, typename... _Args>
55 class out_ptr_t
56 {
57 static_assert(!__is_shared_ptr<_Smart> || sizeof...(_Args) != 0,
58 "a deleter must be used when adapting std::shared_ptr "
59 "with std::out_ptr");
60
61 public:
62 explicit
63 out_ptr_t(_Smart& __smart, _Args... __args)
64 : _M_impl{__smart, std::forward<_Args>(__args)...}
65 {
66 if constexpr (requires { _M_impl._M_out_init(); })
67 _M_impl._M_out_init();
68 }
69
70 out_ptr_t(const out_ptr_t&) = delete;
71
72 ~out_ptr_t() = default;
73
74 operator _Pointer*() const noexcept
75 { return _M_impl._M_get(); }
76
77 operator void**() const noexcept requires (!same_as<_Pointer, void*>)
78 {
79 static_assert(is_pointer_v<_Pointer>);
80 _Pointer* __p = *this;
81 return static_cast<void**>(static_cast<void*>(__p));
82 }
83
84 private:
85 // TODO: Move this to namespace scope? e.g. __detail::_Ptr_adapt_impl
86 template<typename, typename, typename...>
87 struct _Impl
88 {
89 // This constructor must not modify __s because out_ptr_t and
90 // inout_ptr_t want to do different things. After construction
91 // they call _M_out_init() or _M_inout_init() respectively.
92 _Impl(_Smart& __s, _Args&&... __args)
93 : _M_smart(__s), _M_args(std::forward<_Args>(__args)...)
94 { }
95
96 // Called by out_ptr_t to clear the smart pointer before using it.
97 void
98 _M_out_init()
99 {
100 // _GLIBCXX_RESOLVE_LIB_DEFECTS
101 // 3734. Inconsistency in inout_ptr and out_ptr for empty case
102 if constexpr (requires { _M_smart.reset(); })
103 _M_smart.reset();
104 else
105 _M_smart = _Smart();
106 }
107
108 // Called by inout_ptr_t to copy the smart pointer's value
109 // to the pointer that is returned from _M_get().
110 void
111 _M_inout_init()
112 { _M_ptr = _M_smart.release(); }
113
114 // The pointer value returned by operator Pointer*().
115 _Pointer*
116 _M_get() const
117 { return __builtin_addressof(const_cast<_Pointer&>(_M_ptr)); }
118
119 // Finalize the effects on the smart pointer.
120 ~_Impl() noexcept(false);
121
122 _Smart& _M_smart;
123 [[no_unique_address]] _Pointer _M_ptr{};
124 [[no_unique_address]] tuple<_Args...> _M_args;
125 };
126
127 // Partial specialization for raw pointers.
128 template<typename _Tp>
129 struct _Impl<_Tp*, _Tp*>
130 {
131 void
132 _M_out_init()
133 { _M_p = nullptr; }
134
135 void
136 _M_inout_init()
137 { }
138
139 _Tp**
140 _M_get() const
141 { return __builtin_addressof(const_cast<_Tp*&>(_M_p)); }
142
143 _Tp*& _M_p;
144 };
145
146 // Partial specialization for raw pointers, with conversion.
147 template<typename _Tp, typename _Ptr> requires (!is_same_v<_Ptr, _Tp*>)
148 struct _Impl<_Tp*, _Ptr>
149 {
150 explicit
151 _Impl(_Tp*& __p)
152 : _M_p(__p)
153 { }
154
155 void
156 _M_out_init()
157 { _M_p = nullptr; }
158
159 void
160 _M_inout_init()
161 { _M_ptr = _M_p; }
162
163 _Pointer*
164 _M_get() const
165 { return __builtin_addressof(const_cast<_Pointer&>(_M_ptr)); }
166
167 ~_Impl() { _M_p = static_cast<_Tp*>(_M_ptr); }
168
169 _Tp*& _M_p;
170 _Pointer _M_ptr{};
171 };
172
173 // Partial specialization for std::unique_ptr.
174 // This specialization gives direct access to the private member
175 // of the unique_ptr, avoiding the overhead of storing a separate
176 // pointer and then resetting the unique_ptr in the destructor.
177 // FIXME: constrain to only match the primary template,
178 // not program-defined specializations of unique_ptr.
179 template<typename _Tp, typename _Del>
180 struct _Impl<unique_ptr<_Tp, _Del>,
181 typename unique_ptr<_Tp, _Del>::pointer>
182 {
183 void
184 _M_out_init()
185 { _M_smart.reset(); }
186
187 _Pointer*
188 _M_get() const noexcept
189 { return __builtin_addressof(_M_smart._M_t._M_ptr()); }
190
191 _Smart& _M_smart;
192 };
193
194 // Partial specialization for std::unique_ptr with replacement deleter.
195 // FIXME: constrain to only match the primary template,
196 // not program-defined specializations of unique_ptr.
197 template<typename _Tp, typename _Del, typename _Del2>
198 struct _Impl<unique_ptr<_Tp, _Del>,
199 typename unique_ptr<_Tp, _Del>::pointer, _Del2>
200 {
201 void
202 _M_out_init()
203 { _M_smart.reset(); }
204
205 _Pointer*
206 _M_get() const noexcept
207 { return __builtin_addressof(_M_smart._M_t._M_ptr()); }
208
209 ~_Impl()
210 {
211 if (_M_smart.get())
212 _M_smart._M_t._M_deleter() = std::forward<_Del2>(_M_del);
213 }
214
215 _Smart& _M_smart;
216 [[no_unique_address]] _Del2 _M_del;
217 };
218
219 // Partial specialization for std::shared_ptr.
220 // This specialization gives direct access to the private member
221 // of the shared_ptr, avoiding the overhead of storing a separate
222 // pointer and then resetting the shared_ptr in the destructor.
223 // A new control block is allocated in the constructor, so that if
224 // allocation fails it doesn't throw an exception from the destructor.
225 template<typename _Tp, typename _Del, typename _Alloc>
226 requires (is_base_of_v<__shared_ptr<_Tp>, shared_ptr<_Tp>>)
227 struct _Impl<shared_ptr<_Tp>,
228 typename shared_ptr<_Tp>::element_type*, _Del, _Alloc>
229 {
230 _Impl(_Smart& __s, _Del __d, _Alloc __a = _Alloc())
231 : _M_smart(__s)
232 {
233 // We know shared_ptr cannot be used with inout_ptr_t
234 // so we can do all set up here, instead of in _M_out_init().
235 _M_smart.reset();
236
237 // Similar to the shared_ptr(Y*, D, A) constructor, except that if
238 // the allocation throws we do not need (or want) to call deleter.
239 typename _Scd::__allocator_type __a2(__a);
240 auto __mem = __a2.allocate(1);
241 ::new (__mem) _Scd(nullptr, std::forward<_Del>(__d),
242 std::forward<_Alloc>(__a));
243 _M_smart._M_refcount._M_pi = __mem;
244 }
245
246 _Pointer*
247 _M_get() const noexcept
248 { return __builtin_addressof(_M_smart._M_ptr); }
249
250 ~_Impl()
251 {
252 auto& __pi = _M_smart._M_refcount._M_pi;
253
254 if (_Sp __ptr = _M_smart.get())
255 static_cast<_Scd*>(__pi)->_M_impl._M_ptr = __ptr;
256 else // Destroy the control block manually without invoking deleter.
257 std::__exchange(__pi, nullptr)->_M_destroy();
258 }
259
260 _Smart& _M_smart;
261
262 using _Sp = typename _Smart::element_type*;
263 using _Scd = _Sp_counted_deleter<_Sp, decay_t<_Del>,
264 remove_cvref_t<_Alloc>,
265 __default_lock_policy>;
266 };
267
268 // Partial specialization for std::shared_ptr, without custom allocator.
269 template<typename _Tp, typename _Del>
270 requires (is_base_of_v<__shared_ptr<_Tp>, shared_ptr<_Tp>>)
271 struct _Impl<shared_ptr<_Tp>,
272 typename shared_ptr<_Tp>::element_type*, _Del>
273 : _Impl<_Smart, _Pointer, _Del, allocator<void>>
274 {
275 using _Impl<_Smart, _Pointer, _Del, allocator<void>>::_Impl;
276 };
277
278 using _Impl_t = _Impl<_Smart, _Pointer, _Args...>;
279
280 _Impl_t _M_impl;
281
282 template<typename, typename, typename...> friend class inout_ptr_t;
283 };
284
285 /// Smart pointer adaptor for functions taking an inout pointer parameter.
286 /**
287 * @tparam _Smart The type of pointer to adapt.
288 * @tparam _Pointer The type of pointer to convert to.
289 * @tparam _Args... Argument types used when resetting the smart pointer.
290 * @since C++23
291 * @headerfile <memory>
292 */
293 template<typename _Smart, typename _Pointer, typename... _Args>
294 class inout_ptr_t
295 {
296 static_assert(!__is_shared_ptr<_Smart>,
297 "std::inout_ptr can not be used to wrap std::shared_ptr");
298
299 public:
300 explicit
301 inout_ptr_t(_Smart& __smart, _Args... __args)
302 : _M_impl{__smart, std::forward<_Args>(__args)...}
303 {
304 if constexpr (requires { _M_impl._M_inout_init(); })
305 _M_impl._M_inout_init();
306 }
307
308 inout_ptr_t(const inout_ptr_t&) = delete;
309
310 ~inout_ptr_t() = default;
311
312 operator _Pointer*() const noexcept
313 { return _M_impl._M_get(); }
314
315 operator void**() const noexcept requires (!same_as<_Pointer, void*>)
316 {
317 static_assert(is_pointer_v<_Pointer>);
318 _Pointer* __p = *this;
319 return static_cast<void**>(static_cast<void*>(__p));
320 }
321
322 private:
323 // Avoid an invalid instantiation of out_ptr_t<shared_ptr<T>, ...>
324 using _Out_ptr_t
325 = __conditional_t<__is_shared_ptr<_Smart>,
326 out_ptr_t<void*, void*>,
327 out_ptr_t<_Smart, _Pointer, _Args...>>;
328 using _Impl_t = typename _Out_ptr_t::_Impl_t;
329 _Impl_t _M_impl;
330 };
331
332/// @cond undocumented
333namespace __detail
334{
335 // POINTER_OF metafunction
336 template<typename _Tp>
337 consteval auto
338 __pointer_of()
339 {
340 if constexpr (requires { typename _Tp::pointer; })
341 return type_identity<typename _Tp::pointer>{};
342 else if constexpr (requires { typename _Tp::element_type; })
343 return type_identity<typename _Tp::element_type*>{};
344 else
345 {
346 using _Traits = pointer_traits<_Tp>;
347 if constexpr (requires { typename _Traits::element_type; })
348 return type_identity<typename _Traits::element_type*>{};
349 }
350 // else POINTER_OF(S) is not a valid type, return void.
351 }
352
353 // POINTER_OF_OR metafunction
354 template<typename _Smart, typename _Ptr>
355 consteval auto
356 __pointer_of_or()
357 {
358 using _TypeId = decltype(__detail::__pointer_of<_Smart>());
359 if constexpr (is_void_v<_TypeId>)
360 return type_identity<_Ptr>{};
361 else
362 return _TypeId{};
363 }
364
365 // Returns Pointer if !is_void_v<Pointer>, otherwise POINTER_OF(Smart).
366 template<typename _Ptr, typename _Smart>
367 consteval auto
368 __choose_ptr()
369 {
370 if constexpr (!is_void_v<_Ptr>)
371 return type_identity<_Ptr>{};
372 else
373 return __detail::__pointer_of<_Smart>();
374 }
375
376 template<typename _Smart, typename _Sp, typename... _Args>
377 concept __resettable = requires (_Smart& __s) {
378 __s.reset(std::declval<_Sp>(), std::declval<_Args>()...);
379 };
380}
381/// @endcond
382
383 /// Adapt a smart pointer for functions taking an output pointer parameter.
384 /**
385 * @tparam _Pointer The type of pointer to convert to.
386 * @param __s The pointer that should take ownership of the result.
387 * @param __args... Arguments to use when resetting the smart pointer.
388 * @return A std::inout_ptr_t referring to `__s`.
389 * @since C++23
390 * @headerfile <memory>
391 */
392 template<typename _Pointer = void, typename _Smart, typename... _Args>
393 inline auto
394 out_ptr(_Smart& __s, _Args&&... __args)
395 {
396 using _TypeId = decltype(__detail::__choose_ptr<_Pointer, _Smart>());
397 static_assert(!is_void_v<_TypeId>, "first argument to std::out_ptr "
398 "must be a pointer-like type");
399
400 using _Ret = out_ptr_t<_Smart, typename _TypeId::type, _Args&&...>;
401 return _Ret(__s, std::forward<_Args>(__args)...);
402 }
403
404 /// Adapt a smart pointer for functions taking an inout pointer parameter.
405 /**
406 * @tparam _Pointer The type of pointer to convert to.
407 * @param __s The pointer that should take ownership of the result.
408 * @param __args... Arguments to use when resetting the smart pointer.
409 * @return A std::inout_ptr_t referring to `__s`.
410 * @since C++23
411 * @headerfile <memory>
412 */
413 template<typename _Pointer = void, typename _Smart, typename... _Args>
414 inline auto
415 inout_ptr(_Smart& __s, _Args&&... __args)
416 {
417 using _TypeId = decltype(__detail::__choose_ptr<_Pointer, _Smart>());
418 static_assert(!is_void_v<_TypeId>, "first argument to std::inout_ptr "
419 "must be a pointer-like type");
420
421 using _Ret = inout_ptr_t<_Smart, typename _TypeId::type, _Args&&...>;
422 return _Ret(__s, std::forward<_Args>(__args)...);
423 }
424
425 /// @cond undocumented
426 template<typename _Smart, typename _Pointer, typename... _Args>
427 template<typename _Smart2, typename _Pointer2, typename... _Args2>
428 inline
429 out_ptr_t<_Smart, _Pointer, _Args...>::
430 _Impl<_Smart2, _Pointer2, _Args2...>::~_Impl()
431 {
432 using _TypeId = decltype(__detail::__pointer_of_or<_Smart, _Pointer>());
433 using _Sp = typename _TypeId::type;
434
435 if (!_M_ptr)
436 return;
437
438 _Smart& __s = _M_smart;
439 _Pointer& __p = _M_ptr;
440
441 auto __reset = [&](auto&&... __args) {
442 if constexpr (__detail::__resettable<_Smart, _Sp, _Args...>)
443 __s.reset(static_cast<_Sp>(__p), std::forward<_Args>(__args)...);
444 else if constexpr (is_constructible_v<_Smart, _Sp, _Args...>)
445 __s = _Smart(static_cast<_Sp>(__p), std::forward<_Args>(__args)...);
446 else
447 static_assert(is_constructible_v<_Smart, _Sp, _Args...>);
448 };
449
450 if constexpr (sizeof...(_Args) >= 2)
451 std::apply(__reset, std::move(_M_args));
452 else if constexpr (sizeof...(_Args) == 1)
453 __reset(std::get<0>(std::move(_M_args)));
454 else
455 __reset();
456 }
457 /// @endcond
458
459_GLIBCXX_END_NAMESPACE_VERSION
460} // namespace
461
462#endif // __glibcxx_out_ptr
463#endif /* _GLIBCXX_OUT_PTR_H */
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition move.h:126
constexpr _Tp && forward(typename std::remove_reference< _Tp >::type &__t) noexcept
Forward an lvalue.
Definition move.h:70
ISO C++ entities toplevel namespace is std.