libcopp 2.3.1
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
allocator_ptr.h
Go to the documentation of this file.
1// Copyright 2025 owent
2// Created by owent on 2025-03-03
3
4#pragma once
5
6#include <memory>
7
9#include "libcopp/utils/config/libcopp_build_features.h"
11
12LIBCOPP_COPP_NAMESPACE_BEGIN
13namespace memory {
14
16template <class Alloc>
18 using pointer = typename ::std::allocator_traits<Alloc>::pointer;
19 using value_type = typename ::std::allocator_traits<Alloc>::value_type;
20
22 inline allocated_ptr(Alloc& a, pointer p) noexcept : alloc_(&a), ptr_(p) {}
23
25 template <class Ptr, class = nostd::enable_if_t<::std::is_same<Ptr, value_type*>::value>>
26 inline allocated_ptr(Alloc& a, Ptr p) : alloc_(&a), ptr_(p) {}
27
29 inline allocated_ptr(allocated_ptr&& gd) noexcept : alloc_(gd.alloc_), ptr_(gd.ptr_) { gd.ptr_ = nullptr; }
30
32 inline ~allocated_ptr() {
33 if (ptr_ != nullptr) {
34 ::std::allocator_traits<Alloc>::deallocate(*alloc_, ptr_, 1);
35 }
36 }
37
39 inline allocated_ptr& operator=(std::nullptr_t) noexcept {
40 ptr_ = nullptr;
41 return *this;
42 }
43
45 inline value_type* get() noexcept { return ptr_; }
46
47 private:
48 Alloc* alloc_;
50};
51
53template <class Alloc>
55 return {a, ::std::allocator_traits<Alloc>::allocate(a, 1)};
56}
57
58} // namespace memory
59LIBCOPP_COPP_NAMESPACE_END
#define LIBCOPP_UTIL_SYMBOL_VISIBLE
LIBCOPP_UTIL_SYMBOL_VISIBLE allocated_ptr< Alloc > allocate_guarded(Alloc &a)
Allocate space for a single object using a.
Non-standard RAII type for managing pointers obtained from allocators.
allocated_ptr(Alloc &a, pointer p) noexcept
Take ownership of p.
typename ::std::allocator_traits< Alloc >::pointer pointer
typename ::std::allocator_traits< Alloc >::value_type value_type
allocated_ptr & operator=(std::nullptr_t) noexcept
Release ownership of the owned pointer.
~allocated_ptr()
Deallocate the owned pointer.
value_type * get() noexcept
Get the address that the owned pointer refers to.
allocated_ptr(allocated_ptr &&gd) noexcept
Transfer ownership of the owned pointer.
allocated_ptr(Alloc &a, Ptr p)
Convert __ptr to allocator's pointer type and take ownership of it.