C++ 实现高性能内存池

(非线程安全)

一、概述 
C/C++ 中,内存管理是一个非常棘手的问题,我们在编写一个程序的时候几乎不可避免的要遇到内存的分配逻辑,这时候随之而来的有这样一些问题:是否有足够的内存可供分配? 分配失败了怎么办? 如何管理自身的内存使用情况? 等等一系列问题。在一个高可用的软件中,如果我们仅仅单纯的向操作系统去申请内存,当出现内存不足时就退出软件,是明显不合理的。正确的思路应该是在内存不足的时,考虑如何管理并优化自身已经使用的内存,这样才能使得软件变得更加可用。本次项目我们将实现一个内存池,并使用一个栈结构来测试我们的内存池提供的分配性能。最终,我们要实现的内存池在栈结构中的性能,要远高于使用 std::allocator 和 std::vector,如下图所示: 
这里写图片描述

项目涉及的知识点 
C++ 中的内存分配器 std::allocator 
内存池技术 
手动实现模板链式栈 
链式栈和列表栈的性能比较

内存池简介 
内存池是池化技术中的一种形式。通常我们在编写程序的时候回使用 new delete 这些关键字来向操作系统申请内存,而这样造成的后果就是每次申请内存和释放内存的时候,都需要和操作系统的系统调用打交道,从堆中分配所需的内存。如果这样的操作太过频繁,就会找成大量的内存碎片进而降低内存的分配性能,甚至出现内存分配失败的情况。

而内存池就是为了解决这个问题而产生的一种技术。从内存分配的概念上看,内存申请无非就是向内存分配方索要一个指针,当向操作系统申请内存时,操作系统需要进行复杂的内存管理调度之后,才能正确的分配出一个相应的指针。而这个分配的过程中,我们还面临着分配失败的风险。

所以,每一次进行内存分配,就会消耗一次分配内存的时间,设这个时间为 T,那么进行 n 次分配总共消耗的时间就是 nT;如果我们一开始就确定好我们可能需要多少内存,那么在最初的时候就分配好这样的一块内存区域,当我们需要内存的时候,直接从这块已经分配好的内存中使用即可,那么总共需要的分配时间仅仅只有 T。当 n 越大时,节约的时间就越多。

二、主函数设计 
我们要设计实现一个高性能的内存池,那么自然避免不了需要对比已有的内存,而比较内存池对内存的分配性能,就需要实现一个需要对内存进行动态分配的结构(比如:链表栈),为此,可以写出如下的代码:

  1. #include <iostream> // std::cout, std::endl
  2. #include <cassert> // assert()
  3. #include <ctime> // clock()
  4. #include <vector> // std::vector
  5.  
  6. #include "MemoryPool.hpp" // MemoryPool<T>
  7. #include "StackAlloc.hpp" // StackAlloc<T, Alloc>
  8.  
  9. // 插入元素个数
  10. #define ELEMS 10000000
  11. // 重复次数
  12. #define REPS 100
  13.  
  14. int main()
  15. {
  16. clock_t start;
  17.  
  18. // 使用 STL 默认分配器
  19. StackAlloc<int, std::allocator<int> > stackDefault;
  20. start = clock();
  21. for (int j = 0; j < REPS; j++) {
  22. assert(stackDefault.empty());
  23. for (int i = 0; i < ELEMS; i++)
  24. stackDefault.push(i);
  25. for (int i = 0; i < ELEMS; i++)
  26. stackDefault.pop();
  27. }
  28. std::cout << "Default Allocator Time: ";
  29. std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "nn";
  30.  
  31. // 使用内存池
  32. StackAlloc<int, MemoryPool<int> > stackPool;
  33. start = clock();
  34. for (int j = 0; j < REPS; j++) {
  35. assert(stackPool.empty());
  36. for (int i = 0; i < ELEMS; i++)
  37. stackPool.push(i);
  38. for (int i = 0; i < ELEMS; i++)
  39. stackPool.pop();
  40. }
  41. std::cout << "MemoryPool Allocator Time: ";
  42. std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "nn";
  43.  
  44. return 0;
  45. }

在上面的两段代码中,StackAlloc 是一个链表栈,接受两个模板参数,第一个参数是栈中的元素类型,第二个参数就是栈使用的内存分配器。

因此,这个内存分配器的模板参数就是整个比较过程中唯一的变量,使用默认分配器的模板参数为 std::allocator,而使用内存池的模板参数为 MemoryPool。

std::allocator 是 C++标准库中提供的默认分配器,他的特点就在于我们在 使用 new 来申请内存构造新对象的时候,势必要调用类对象的默认构造函数,而使用 std::allocator 则可以将内存分配和对象的构造这两部分逻辑给分离开来,使得分配的内存是原始、未构造的。
  • 1

下面我们来实现这个链表栈。

三、模板链表栈

栈的结构非常的简单,没有什么复杂的逻辑操作,其成员函数只需要考虑两个基本的操作:入栈、出栈。为了操作上的方便,我们可能还需要这样一些方法:判断栈是否空、清空栈、获得栈顶元素。

  1. #include <memory>
  2. template <typename T>
  3. struct StackNode_
  4. {
  5. T data;
  6. StackNode_* prev;
  7. };
  8. // T 为存储的对象类型, Alloc 为使用的分配器, 并默认使用 std::allocator 作为对象的分配器
  9. template <typename T, typename Alloc = std::allocator<T> >
  10. class StackAlloc
  11. {
  12. public:
  13. // 使用 typedef 简化类型名
  14. typedef StackNode_<T> Node;
  15. typedef typename Alloc::template rebind<Node>::other allocator;
  16.  
  17. // 默认构造
  18. StackAlloc() { head_ = 0; }
  19. // 默认析构
  20. ~StackAlloc() { clear(); }
  21.  
  22. // 当栈中元素为空时返回 true
  23. bool empty() {return (head_ == 0);}
  24.  
  25. // 释放栈中元素的所有内存
  26. void clear();
  27.  
  28. // 压栈
  29. void push(T element);
  30.  
  31. // 出栈
  32. T pop();
  33.  
  34. // 返回栈顶元素
  35. T top() { return (head_->data); }
  36.  
  37. private:
  38. //
  39. allocator allocator_;
  40. // 栈顶
  41. Node* head_;
  42. };

简单的逻辑诸如构造、析构、判断栈是否空、返回栈顶元素的逻辑都非常简单,直接在上面的定义中实现了,下面我们来实现 clear(), push() 和 pop() 这三个重要的逻辑:

  1. // 释放栈中元素的所有内存
  2. void clear() {
  3. Node* curr = head_;
  4. // 依次出栈
  5. while (curr != 0)
  6. {
  7. Node* tmp = curr->prev;
  8. // 先析构, 再回收内存
  9. allocator_.destroy(curr);
  10. allocator_.deallocate(curr, 1);
  11. curr = tmp;
  12. }
  13. head_ = 0;
  14. }
  15. // 入栈
  16. void push(T element) {
  17. // 为一个节点分配内存
  18. Node* newNode = allocator_.allocate(1);
  19. // 调用节点的构造函数
  20. allocator_.construct(newNode, Node());
  21.  
  22. // 入栈操作
  23. newNode->data = element;
  24. newNode->prev = head_;
  25. head_ = newNode;
  26. }
  27.  
  28. // 出栈
  29. T pop() {
  30. // 出栈操作 返回出栈元素
  31. T result = head_->data;
  32. Node* tmp = head_->prev;
  33. allocator_.destroy(head_);
  34. allocator_.deallocate(head_, 1);
  35. head_ = tmp;
  36. return result;
  37. }

至此,我们完成了整个模板链表栈,现在我们可以先注释掉 main() 函数中使用内存池部分的代码来测试这个连表栈的内存分配情况,我们就能够得到这样的结果:

这里写图片描述

在使用 std::allocator 的默认内存分配器中,在

  1. #define ELEMS 10000000
  2. #define REPS 100
  • 1
  • 2

的条件下,总共花费了近一分钟的时间。

如果觉得花费的时间较长,不愿等待,则你尝试可以减小这两个值
  • 1

总结

本节我们实现了一个用于测试性能比较的模板链表栈,目前的代码如下。在下一节中,我们开始详细实现我们的高性能内存池。

  1. // StackAlloc.hpp
  2.  
  3. #ifndef STACK_ALLOC_H
  4. #define STACK_ALLOC_H
  5.  
  6. #include <memory>
  7.  
  8. template <typename T>
  9. struct StackNode_
  10. {
  11. T data;
  12. StackNode_* prev;
  13. };
  14.  
  15. // T 为存储的对象类型, Alloc 为使用的分配器,
  16. // 并默认使用 std::allocator 作为对象的分配器
  17. template <class T, class Alloc = std::allocator<T> >
  18. class StackAlloc
  19. {
  20. public:
  21. // 使用 typedef 简化类型名
  22. typedef StackNode_<T> Node;
  23. typedef typename Alloc::template rebind<Node>::other allocator;
  24. // 默认构造
  25. StackAlloc() { head_ = 0; }
  26. // 默认析构
  27. ~StackAlloc() { clear(); }
  28. // 当栈中元素为空时返回 true
  29. bool empty() {return (head_ == 0);}
  30.  
  31. // 释放栈中元素的所有内存
  32. void clear() {
  33. Node* curr = head_;
  34. while (curr != 0)
  35. {
  36. Node* tmp = curr->prev;
  37. allocator_.destroy(curr);
  38. allocator_.deallocate(curr, 1);
  39. curr = tmp;
  40. }
  41. head_ = 0;
  42. }
  43.  
  44. // 入栈
  45. void push(T element) {
  46. // 为一个节点分配内存
  47. Node* newNode = allocator_.allocate(1);
  48. // 调用节点的构造函数
  49. allocator_.construct(newNode, Node());
  50.  
  51. // 入栈操作
  52. newNode->data = element;
  53. newNode->prev = head_;
  54. head_ = newNode;
  55. }
  56.  
  57. // 出栈
  58. T pop() {
  59. // 出栈操作 返回出栈结果
  60. T result = head_->data;
  61. Node* tmp = head_->prev;
  62. allocator_.destroy(head_);
  63. allocator_.deallocate(head_, 1);
  64. head_ = tmp;
  65. return result;
  66. }
  67.  
  68. // 返回栈顶元素
  69. T top() { return (head_->data); }
  70.  
  71. private:
  72. allocator allocator_;
  73. Node* head_;
  74. };
  75.  
  76. #endif // STACK_ALLOC_H
  77.  
    // main.cpp
  78.  
  79. #include <iostream>
  80. #include <cassert>
  81. #include <ctime>
  82. #include <vector>
  83.  
  84. // #include "MemoryPool.hpp"
  85. #include "StackAlloc.hpp"
  86.  
  87. // 根据电脑性能调整这些值
  88. // 插入元素个数
  89. #define ELEMS 25000000
  90. // 重复次数
  91. #define REPS 50
  92.  
  93. int main()
  94. {
  95. clock_t start;
  96.  
  97. // 使用默认分配器
  98. StackAlloc<int, std::allocator<int> > stackDefault;
  99. start = clock();
  100. for (int j = 0; j < REPS; j++) {
  101. assert(stackDefault.empty());
  102. for (int i = 0; i < ELEMS; i++)
  103. stackDefault.push(i);
  104. for (int i = 0; i < ELEMS; i++)
  105. stackDefault.pop();
  106. }
  107. std::cout << "Default Allocator Time: ";
  108. std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "nn";
  109.  
  110. // 使用内存池
  111. // StackAlloc<int, MemoryPool<int> > stackPool;
  112. // start = clock();
  113. // for (int j = 0; j < REPS; j++) {
  114. // assert(stackPool.empty());
  115. // for (int i = 0; i < ELEMS; i++)
  116. // stackPool.push(i);
  117. // for (int i = 0; i < ELEMS; i++)
  118. // stackPool.pop();
  119. // }
  120. // std::cout << "MemoryPool Allocator Time: ";
  121. // std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "nn";
  122.  
  123. return 0;
  124. }

二、设计内存池 
在上一节实验中,我们在模板链表栈中使用了默认构造器来管理栈操作中的元素内存,一共涉及到了 rebind::other, allocate(), dealocate(), construct(), destroy()这些关键性的接口。所以为了让代码直接可用,我们同样应该在内存池中设计同样的接口:

  1.  
    #ifndef MEMORY_POOL_HPP
  2.  
    #define MEMORY_POOL_HPP
  3.  
     
  4.  
    #include <climits>
  5.  
    #include <cstddef>
  6.  
     
  7.  
    template <typename T, size_t BlockSize = 4096>
  8.  
    class MemoryPool
  9.  
    {
  10.  
    public:
  11.  
    // 使用 typedef 简化类型书写
  12.  
    typedef T* pointer;
  13.  
     
  14.  
    // 定义 rebind<U>::other 接口
  15.  
    template <typename U> struct rebind {
  16.  
    typedef MemoryPool<U> other;
  17.  
    };
  18.  
     
  19.  
    // 默认构造, 初始化所有的槽指针
  20.  
    // C++11 使用了 noexcept 来显式的声明此函数不会抛出异常
  21.  
    MemoryPool() noexcept {
  22.  
    currentBlock_ = nullptr;
  23.  
    currentSlot_ = nullptr;
  24.  
    lastSlot_ = nullptr;
  25.  
    freeSlots_ = nullptr;
  26.  
    }
  27.  
     
  28.  
    // 销毁一个现有的内存池
  29.  
    ~MemoryPool() noexcept;
  30.  
     
  31.  
    // 同一时间只能分配一个对象, n 和 hint 会被忽略
  32.  
    pointer allocate(size_t n = 1, const T* hint = 0);
  33.  
     
  34.  
    // 销毁指针 p 指向的内存区块
  35.  
    void deallocate(pointer p, size_t n = 1);
  36.  
     
  37.  
    // 调用构造函数
  38.  
    template <typename U, typename... Args>
  39.  
    void construct(U* p, Args&&... args);
  40.  
     
  41.  
    // 销毁内存池中的对象, 即调用对象的析构函数
  42.  
    template <typename U>
  43.  
    void destroy(U* p) {
  44.  
    p->~U();
  45.  
    }
  46.  
     
  47.  
    private:
  48.  
    // 用于存储内存池中的对象槽,
  49.  
    // 要么被实例化为一个存放对象的槽,
  50.  
    // 要么被实例化为一个指向存放对象槽的槽指针
  51.  
    union Slot_ {
  52.  
    T element;
  53.  
    Slot_* next;
  54.  
    };
  55.  
     
  56.  
    // 数据指针
  57.  
    typedef char* data_pointer_;
  58.  
    // 对象槽
  59.  
    typedef Slot_ slot_type_;
  60.  
    // 对象槽指针
  61.  
    typedef Slot_* slot_pointer_;
  62.  
     
  63.  
    // 指向当前内存区块
  64.  
    slot_pointer_ currentBlock_;
  65.  
    // 指向当前内存区块的一个对象槽
  66.  
    slot_pointer_ currentSlot_;
  67.  
    // 指向当前内存区块的最后一个对象槽
  68.  
    slot_pointer_ lastSlot_;
  69.  
    // 指向当前内存区块中的空闲对象槽
  70.  
    slot_pointer_ freeSlots_;
  71.  
     
  72.  
    // 检查定义的内存池大小是否过小
  73.  
    static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small.");
  74.  
    };
  75.  
     
  76.  
    #endif // MEMORY_POOL_HPP

在上面的类设计中可以看到,在这个内存池中,其实是使用链表来管理整个内存池的内存区块的。内存池首先会定义固定大小的基本内存区块(Block),然后在其中定义了一个可以实例化为存放对象内存槽的对象槽(Slot_)和对象槽指针的一个联合。然后在区块中,定义了四个关键性质的指针,它们的作用分别是:

currentBlock_: 指向当前内存区块的指针 
currentSlot_: 指向当前内存区块中的对象槽 
lastSlot_: 指向当前内存区块中的最后一个对象槽 
freeSlots_: 指向当前内存区块中所有空闲的对象槽 
梳理好整个内存池的设计结构之后,我们就可以开始实现关键性的逻辑了。

三、实现

MemoryPool::construct() 实现

MemoryPool::construct() 的逻辑是最简单的,我们需要实现的,仅仅只是调用信件对象的构造函数即可,因此:

  1.  
    // 调用构造函数, 使用 std::forward 转发变参模板
  2.  
    template <typename U, typename... Args>
  3.  
    void construct(U* p, Args&&... args) {
  4.  
    new (p) U (std::forward<Args>(args)...);
  5.  
    }
  • 1
  • 2
  • 3
  • 4
  • 5

MemoryPool::deallocate() 实现

MemoryPool::deallocate() 是在对象槽中的对象被析构后才会被调用的,主要目的是销毁内存槽。其逻辑也不复杂:

  1.  
    // 销毁指针 p 指向的内存区块
  2.  
    void deallocate(pointer p, size_t n = 1) {
  3.  
    if (p != nullptr) {
  4.  
    // reinterpret_cast 是强制类型转换符
  5.  
    // 要访问 next 必须强制将 p 转成 slot_pointer_
  6.  
    reinterpret_cast<slot_pointer_>(p)->next = freeSlots_;
  7.  
    freeSlots_ = reinterpret_cast<slot_pointer_>(p);
  8.  
    }
  9.  
    }

MemoryPool::~MemoryPool() 实现

析构函数负责销毁整个内存池,因此我们需要逐个删除掉最初向操作系统申请的内存块:

  1.  
    // 销毁一个现有的内存池
  2.  
    ~MemoryPool() noexcept {
  3.  
    // 循环销毁内存池中分配的内存区块
  4.  
    slot_pointer_ curr = currentBlock_;
  5.  
    while (curr != nullptr) {
  6.  
    slot_pointer_ prev = curr->next;
  7.  
    operator delete(reinterpret_cast<void*>(curr));
  8.  
    curr = prev;
  9.  
    }
  10.  
    }

MemoryPool::allocate() 实现

MemoryPool::allocate() 毫无疑问是整个内存池的关键所在,但实际上理清了整个内存池的设计之后,其实现并不复杂。具体实现如下:

  1.  
    // 同一时间只能分配一个对象, n 和 hint 会被忽略
  2.  
    pointer allocate(size_t n = 1, const T* hint = 0) {
  3.  
    // 如果有空闲的对象槽,那么直接将空闲区域交付出去
  4.  
    if (freeSlots_ != nullptr) {
  5.  
    pointer result = reinterpret_cast<pointer>(freeSlots_);
  6.  
    freeSlots_ = freeSlots_->next;
  7.  
    return result;
  8.  
    } else {
  9.  
    // 如果对象槽不够用了,则分配一个新的内存区块
  10.  
    if (currentSlot_ >= lastSlot_) {
  11.  
    // 分配一个新的内存区块,并指向前一个内存区块
  12.  
    data_pointer_ newBlock = reinterpret_cast<data_pointer_>(operator new(BlockSize));
  13.  
    reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_;
  14.  
    currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock);
  15.  
    // 填补整个区块来满足元素内存区域的对齐要求
  16.  
    data_pointer_ body = newBlock + sizeof(slot_pointer_);
  17.  
    uintptr_t result = reinterpret_cast<uintptr_t>(body);
  18.  
    size_t bodyPadding = (alignof(slot_type_) - result) % alignof(slot_type_);
  19.  
    currentSlot_ = reinterpret_cast<slot_pointer_>(body + bodyPadding);
  20.  
    lastSlot_ = reinterpret_cast<slot_pointer_>(newBlock + BlockSize - sizeof(slot_type_) + 1);
  21.  
    }
  22.  
    return reinterpret_cast<pointer>(currentSlot_++);
  23.  
    }
  24.  
    }

四、与 std::vector 的性能对比

我们知道,对于栈来说,链栈其实并不是最好的实现方式,因为这种结构的栈不可避免的会涉及到指针相关的操作,同时,还会消耗一定量的空间来存放节点之间的指针。事实上,我们可以使用 std::vector 中的 push_back() 和 pop_back() 这两个操作来模拟一个栈,我们不妨来对比一下这个 std::vector 与我们所实现的内存池在性能上谁高谁低,我们在 主函数中加入如下代码:

  1.  
    // 比较内存池和 std::vector 之间的性能
  2.  
    std::vector<int> stackVector;
  3.  
    start = clock();
  4.  
    for (int j = 0; j < REPS; j++) {
  5.  
    assert(stackVector.empty());
  6.  
    for (int i = 0; i < ELEMS; i++)
  7.  
    stackVector.push_back(i);
  8.  
    for (int i = 0; i < ELEMS; i++)
  9.  
    stackVector.pop_back();
  10.  
    }
  11.  
    std::cout << "Vector Time: ";
  12.  
    std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "nn";

这时候,我们重新编译代码,就能够看出这里面的差距了: 
这里写图片描述 
首先是使用默认分配器的链表栈速度最慢,其次是使用 std::vector 模拟的栈结构,在链表栈的基础上大幅度削减了时间。

std::vector 的实现方式其实和内存池较为类似,在 std::vector 空间不够用时,会抛弃现在的内存区域重新申请一块更大的区域,并将现在内存区域中的数据整体拷贝一份到新区域中。
  • 1

最后,对于我们实现的内存池,消耗的时间最少,即内存分配性能最佳,完成了本项目。

总结

本节中,我们实现了我们上节实验中未实现的内存池,完成了整个项目的目标。 这个内存池不仅精简而且高效,整个内存池的完整代码如下:

  1.  
    #ifndef MEMORY_POOL_HPP
  2.  
    #define MEMORY_POOL_HPP
  3.  
     
  4.  
    #include <climits>
  5.  
    #include <cstddef>
  6.  
     
  7.  
    template <typename T, size_t BlockSize = 4096>
  8.  
    class MemoryPool
  9.  
    {
  10.  
    public:
  11.  
    // 使用 typedef 简化类型书写
  12.  
    typedef T* pointer;
  13.  
     
  14.  
    // 定义 rebind<U>::other 接口
  15.  
    template <typename U> struct rebind {
  16.  
    typedef MemoryPool<U> other;
  17.  
    };
  18.  
     
  19.  
    // 默认构造
  20.  
    // C++11 使用了 noexcept 来显式的声明此函数不会抛出异常
  21.  
    MemoryPool() noexcept {
  22.  
    currentBlock_ = nullptr;
  23.  
    currentSlot_ = nullptr;
  24.  
    lastSlot_ = nullptr;
  25.  
    freeSlots_ = nullptr;
  26.  
    }
  27.  
     
  28.  
    // 销毁一个现有的内存池
  29.  
    ~MemoryPool() noexcept {
  30.  
    // 循环销毁内存池中分配的内存区块
  31.  
    slot_pointer_ curr = currentBlock_;
  32.  
    while (curr != nullptr) {
  33.  
    slot_pointer_ prev = curr->next;
  34.  
    operator delete(reinterpret_cast<void*>(curr));
  35.  
    curr = prev;
  36.  
    }
  37.  
    }
  38.  
     
  39.  
    // 同一时间只能分配一个对象, n 和 hint 会被忽略
  40.  
    pointer allocate(size_t n = 1, const T* hint = 0) {
  41.  
    if (freeSlots_ != nullptr) {
  42.  
    pointer result = reinterpret_cast<pointer>(freeSlots_);
  43.  
    freeSlots_ = freeSlots_->next;
  44.  
    return result;
  45.  
    }
  46.  
    else {
  47.  
    if (currentSlot_ >= lastSlot_) {
  48.  
    // 分配一个内存区块
  49.  
    data_pointer_ newBlock = reinterpret_cast<data_pointer_>(operator new(BlockSize));
  50.  
    reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_;
  51.  
    currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock);
  52.  
    data_pointer_ body = newBlock + sizeof(slot_pointer_);
  53.  
    uintptr_t result = reinterpret_cast<uintptr_t>(body);
  54.  
    size_t bodyPadding = (alignof(slot_type_) - result) % alignof(slot_type_);
  55.  
    currentSlot_ = reinterpret_cast<slot_pointer_>(body + bodyPadding);
  56.  
    lastSlot_ = reinterpret_cast<slot_pointer_>(newBlock + BlockSize - sizeof(slot_type_) + 1);
  57.  
    }
  58.  
    return reinterpret_cast<pointer>(currentSlot_++);
  59.  
    }
  60.  
    }
  61.  
     
  62.  
    // 销毁指针 p 指向的内存区块
  63.  
    void deallocate(pointer p, size_t n = 1) {
  64.  
    if (p != nullptr) {
  65.  
    reinterpret_cast<slot_pointer_>(p)->next = freeSlots_;
  66.  
    freeSlots_ = reinterpret_cast<slot_pointer_>(p);
  67.  
    }
  68.  
    }
  69.  
     
  70.  
    // 调用构造函数, 使用 std::forward 转发变参模板
  71.  
    template <typename U, typename... Args>
  72.  
    void construct(U* p, Args&&... args) {
  73.  
    new (p) U (std::forward<Args>(args)...);
  74.  
    }
  75.  
     
  76.  
    // 销毁内存池中的对象, 即调用对象的析构函数
  77.  
    template <typename U>
  78.  
    void destroy(U* p) {
  79.  
    p->~U();
  80.  
    }
  81.  
     
  82.  
    private:
  83.  
    // 用于存储内存池中的对象槽
  84.  
    union Slot_ {
  85.  
    T element;
  86.  
    Slot_* next;
  87.  
    };
  88.  
     
  89.  
    // 数据指针
  90.  
    typedef char* data_pointer_;
  91.  
    // 对象槽
  92.  
    typedef Slot_ slot_type_;
  93.  
    // 对象槽指针
  94.  
    typedef Slot_* slot_pointer_;
  95.  
     
  96.  
    // 指向当前内存区块
  97.  
    slot_pointer_ currentBlock_;
  98.  
    // 指向当前内存区块的一个对象槽
  99.  
    slot_pointer_ currentSlot_;
  100.  
    // 指向当前内存区块的最后一个对象槽
  101.  
    slot_pointer_ lastSlot_;
  102.  
    // 指向当前内存区块中的空闲对象槽
  103.  
    slot_pointer_ freeSlots_;
  104.  
    // 检查定义的内存池大小是否过小
  105.  
    static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small.");
  106.  
    };
  107.  
     
  108.  
    #endif // MEMORY_POOL_HPP

实验来源:https://www.shiyanlou.com/courses/running 
项目来源:https://github.com/cacay/MemoryPool

原文链接: https://www.cnblogs.com/abelchao/p/11843410.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 实现高性能内存池

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/305782

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午3:07
下一篇 2023年2月16日 上午3:08

相关推荐