iceoryx中的工具类


iceoryx中的工具类如:BumpAllocator,RelativePointer等代码分析

BumpAllocator

  • 简要介绍:BumpAllocator类是一个自定义的内存分配器。它自己不分配内存,分配的是已经申请好的内存,且不对这块内存生命明周期有任何的管理。
  • 原理:这个分配器的工作原理是将一大块内存分割成许多小块,并将其分配给需要内存的对象。每当有请求分配内存的调用时,它就简单地返回一个指向内存块中未使用部分的指针,并将内部的指针向前推进以准备下一次分配。
  • 特点:这种分配策略非常快速,因为它仅涉及一次指针增加操作,而不需要进行任何复杂的内存管理或垃圾收集。
  • 限制:一旦内存被分配出去,就无法回收和重用,除非整个分配器被重置。
  • 适用场景:适合于生命周期明确的短期对象,或者在程序的特定阶段一次性分配所有所需内存的情况。

内存分配如下图:
在这里插入图片描述

代码

  • 构造函数中初始化内存地址和长度:
BumpAllocator::BumpAllocator(void* const startAddress, const uint64_t length) noexcept
    : m_startAddress(reinterpret_cast<uint64_t>(startAddress))
    , m_length(length)
{
   
}
  • 核心成员函数allocate负责分配内存:
expected<void*, BumpAllocatorError> BumpAllocator::allocate(const uint64_t size, const uint64_t alignment) noexcept
{
   
    if (size == 0)
    {
   
        IOX_LOG(WARN) << "Cannot allocate memory of size 0.";
        return err(BumpAllocatorError::REQUESTED_ZERO_SIZED_MEMORY);
    }

    const uint64_t currentAddress{
   m_startAddress + m_currentPosition};
    uint64_t alignedPosition{
   align(currentAddress, alignment)};

    alignedPosition -= m_startAddress;

    void* allocation{
   nullptr};

    const uint64_t nextPosition{
   alignedPosition + size};
    if (m_length >= nextPosition)
    {
   
        allocation = reinterpret_cast<void*>(m_startAddress + alignedPosition);
        m_currentPosition = nextPosition;
    }
    else
    {
   
        return err(BumpAllocatorError::OUT_OF_MEMORY);
    }

    return ok(allocation);
}
  • 成员函数deallocate重置当前位置到起始地址
void BumpAllocator::deallocate() noexcept
{
   
    m_currentPosition = 0;
}

RelativePointer

相关推荐

  1. redis工具详细

    2023-12-08 03:44:06       30 阅读
  2. Springboot常用工具

    2023-12-08 03:44:06       17 阅读
  3. Hutool工具包Validator数据校验

    2023-12-08 03:44:06       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-08 03:44:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-08 03:44:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-08 03:44:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-08 03:44:06       18 阅读

热门阅读

  1. 股票怎么加杠杆买入

    2023-12-08 03:44:06       32 阅读
  2. Web3之L2 ZK-Rollup 方案-StarkNet

    2023-12-08 03:44:06       38 阅读
  3. 存储过程与视图

    2023-12-08 03:44:06       37 阅读
  4. 【UGUI】实现UGUI背包系统的六个主要交互功能

    2023-12-08 03:44:06       39 阅读
  5. deepin v20 在线安装docker

    2023-12-08 03:44:06       39 阅读
  6. vue中字典的使用

    2023-12-08 03:44:06       38 阅读