iceoryx中的工具类

本文分析了iceoryx库中的BumpAllocator内存分配器,它是一种快速分配已申请内存的策略,适用于短期对象。同时介绍了辅助类RelativePointer。BumpAllocator通过构造函数初始化内存地址和长度,核心功能包括allocate和deallocate方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值