C++ std::shared_ptr自定义allocator引入内存池

当C++项目里做了大量的动态内存分配与释放,可能会导致内存碎片,使系统性能降低。当动态内存分配的开销变得不容忽视时,一种解决办法是一次从操作系统分配一块大的静态内存作为内存池进行手动管理,堆对象内存分配时从内存池中分配一块类对象大小的内存,释放时并不实际将内存归还给操作系统,而是交给自定义的内存管理模块处理。本文介绍基于std::shared_ptr自定义allocator引入内存池的方法。

在这里插入图片描述

公众号:七昂的技术之旅

尝试重写new和delete运算符

项目中大量使用std::shared_ptr且与多个模块耦合, 如果直接将 std::shared_ptr 重构为手动管理裸指针的实现,改动量太大,而且可能会带来不可预料的问题。于是尝试了重写new和delete运算符并添加了打印,发现 std::shared_ptr 的创建并不会直接调用 newdelete, 原因在于std::shared_ptr 有自己的内存分配机制。

std::allocate_shared

于是,想到了STL的一大组件 Allocator。C++提供了 std::alloc_shared 函数,可以自定义std::shared_ptr 的内存分配方式,其定义如下:

std::allocate_shared<T>(custom_alloc, std::forward<Args>(args)...);

仅需传入自定义分配器allocator和T的构造参数列表。

实际上, std::make_shared 就是对以上函数进行了封装,使用了默认的分配器。

MemoryPool的使用

内存池直接采用了相关开源项目的定义:

可以选用

https://github.com/DevShiftTeam/AppShift-MemoryPool

Fast Efficient Fixed-Sized Memory Pool

MemoryPoolManager 管理内存池的类

  1. 分配内存池

内存池需要拥有静态生命周期,因此将内存池管理类 MemoryPoolManager 设计为全局单例模式实现,定义Alloc()Free() 方法,实现了内存池与自定义分配器解耦。

  1. 引入自旋锁实现线程安全

由于使用的相关开源内存池不是线程安全的,因此引入了自旋锁在内存池做内存分配和释放时加锁。自旋锁采用了以下文章中的实现:

Correctly implementing a spinlock in C++

MemoryPoolManager 的完整实现如下:


class MemoryPoolManager {
   
public:
	static MemoryPoolManager& GetInstance();
	void* Alloc(size_t sz);
	void Free(void* p);
	~MemoryPoolManager();
private:
	MemoryPoolManager();
	MemoryPoolManager(const MemoryPoolManager
这个错误通常是因为尝试将一个类型为`std::shared_ptr<rclcpp::Subscription<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>>>>`的变量赋值给一个类型为`std::shared_ptr<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>>`的变量,这两个类型虽然都是指向`rclcpp::Subscription`的`shared_ptr`,但是模板参数不同,无法直接赋值。 解决方法是将两个类型匹配,可以通过使用`std::static_pointer_cast`将其中一个类型转换成另一个类型,例如: ``` std::shared_ptr<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>> sub; std::shared_ptr<rclcpp::Subscription<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<const std::shared_ptr<std_msgs::msg::String_<std::allocator<void>>> &, std::allocator<void>>>> sub_const; // 将 sub_const 转换成 sub 的类型 sub = std::static_pointer_cast<rclcpp::Subscription<std_msgs::msg::String, std::allocator<void>, rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::String, std::allocator<void>>>>(sub_const); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值