15 #ifndef RCLCPP__ALLOCATOR__ALLOCATOR_COMMON_HPP_
16 #define RCLCPP__ALLOCATOR__ALLOCATOR_COMMON_HPP_
23 #include "rclcpp/allocator/allocator_deleter.hpp"
30 template<
typename T,
typename Alloc>
31 using AllocRebind =
typename std::allocator_traits<Alloc>::template rebind_traits<T>;
33 template<
typename Alloc>
34 void * retyped_allocate(
size_t size,
void * untyped_allocator)
36 auto typed_allocator =
static_cast<Alloc *
>(untyped_allocator);
37 if (!typed_allocator) {
38 throw std::runtime_error(
"Received incorrect allocator type");
40 return std::allocator_traits<Alloc>::allocate(*typed_allocator, size);
43 template<
typename Alloc>
44 void * retyped_zero_allocate(
size_t number_of_elem,
size_t size_of_elem,
void * untyped_allocator)
46 auto typed_allocator =
static_cast<Alloc *
>(untyped_allocator);
47 if (!typed_allocator) {
48 throw std::runtime_error(
"Received incorrect allocator type");
50 size_t size = number_of_elem * size_of_elem;
51 void * allocated_memory =
52 std::allocator_traits<Alloc>::allocate(*typed_allocator, size);
53 if (allocated_memory) {
54 std::memset(allocated_memory, 0, size);
56 return allocated_memory;
59 template<
typename T,
typename Alloc>
60 void retyped_deallocate(
void * untyped_pointer,
void * untyped_allocator)
62 auto typed_allocator =
static_cast<Alloc *
>(untyped_allocator);
63 if (!typed_allocator) {
64 throw std::runtime_error(
"Received incorrect allocator type");
66 auto typed_ptr =
static_cast<T *
>(untyped_pointer);
67 std::allocator_traits<Alloc>::deallocate(*typed_allocator, typed_ptr, 1);
70 template<
typename T,
typename Alloc>
71 void * retyped_reallocate(
void * untyped_pointer,
size_t size,
void * untyped_allocator)
73 auto typed_allocator =
static_cast<Alloc *
>(untyped_allocator);
74 if (!typed_allocator) {
75 throw std::runtime_error(
"Received incorrect allocator type");
77 auto typed_ptr =
static_cast<T *
>(untyped_pointer);
78 std::allocator_traits<Alloc>::deallocate(*typed_allocator, typed_ptr, 1);
79 return std::allocator_traits<Alloc>::allocate(*typed_allocator, size);
87 typename std::enable_if<!std::is_same<Alloc, std::allocator<void>>::value>::type * =
nullptr>
92 rcl_allocator.allocate = &retyped_allocate<Alloc>;
93 rcl_allocator.zero_allocate = &retyped_zero_allocate<Alloc>;
94 rcl_allocator.deallocate = &retyped_deallocate<T, Alloc>;
95 rcl_allocator.reallocate = &retyped_reallocate<T, Alloc>;
96 rcl_allocator.state = &allocator;
100 return rcl_allocator;
107 typename std::enable_if<std::is_same<Alloc, std::allocator<void>>::value>::type * =
nullptr>
#define rcl_get_default_allocator
Return a properly initialized rcl_allocator_t with default values.
rcutils_allocator_t rcl_allocator_t
Encapsulation of an allocator.
Versions of rosidl_typesupport_cpp::get_message_type_support_handle that handle adapted types.