c++ - 创建发布者 ROS2 中的分配器
问题描述
根据ROS2 文档,有第三个参数称为分配器,可以在创建发布者时使用。如何使用这个分配器?它是否为发布者分配内存?
std::shared_ptr< PublisherT > rclcpp::node::Node::create_publisher ( const std::string & topic_name,
const rmw_qos_profile_t & qos_profile = rmw_qos_profile_default,
std::shared_ptr< Alloc > allocator = nullptr
)
解决方案
自定义分配器将用于发布者上下文中的所有堆分配。这与您使用自定义分配器的方式相同,如此处std::vector
所示。对于 ROS2,以自定义分配器为例。
template<typename T>
struct pointer_traits {
using reference = T &;
using const_reference = const T &;
};
// Avoid declaring a reference to void with an empty specialization
template<>
struct pointer_traits<void> {
};
template<typename T = void>
struct MyAllocator : public pointer_traits<T> {
public:
using value_type = T;
using size_type = std::size_t;
using pointer = T *;
using const_pointer = const T *;
using difference_type = typename std::pointer_traits<pointer>::difference_type;
MyAllocator() noexcept;
~MyAllocator() noexcept;
template<typename U>
MyAllocator(const MyAllocator<U> &) noexcept;
T * allocate(size_t size, const void * = 0);
void deallocate(T * ptr, size_t size);
template<typename U>
struct rebind {
typedef MyAllocator<U> other;
};
};
template<typename T, typename U>
constexpr bool operator==(const MyAllocator<T> &,
const MyAllocator<U> &) noexcept;
template<typename T, typename U>
constexpr bool operator!=(const MyAllocator<T> &,
const MyAllocator<U> &) noexcept;
然后,您的主要设置看起来与没有自定义分配器的情况基本相同。
auto alloc = std::make_shared<MyAllocator<void>>();
auto publisher = node->create_publisher<std_msgs::msg::UInt32>("allocator_example", 10, alloc);
auto msg_mem_strat =
std::make_shared<rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::UInt32,
MyAllocator<>>>(alloc);
std::shared_ptr<rclcpp::memory_strategy::MemoryStrategy> memory_strategy =
std::make_shared<AllocatorMemoryStrategy<MyAllocator<>>>(alloc);
推荐阅读
- couchbase - 如何使用函数或运算符迭代 Couchbase 中的记录
- java - postgresql 日期与 java Instant
- msbuild - Visual Studio 2017 - 如何使用附加的 DLL(不是文件)进行构建
- spring - 如何在应用程序中具有 JPA 的 Spring Boot 中使用 ElasticSearch,我是否必须从表中获取记录并将其放入 elasticsearch 的索引中?
- python - 使用 python3 指定放置下载文件的路径
- lua - Lua表成员函数在哪里定义
- c# - 无法加载类型 Microsoft.Bot.Builder.Internals.Fibers.SetField
- windows - 强制 Windows 进程更新其配置的方法(重新读取其注册表设置)
- json - REST 调用响应 HTTPS 状态 415
- python - 计算 if 循环的迭代次数