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) << "\n\n";
  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) << "\n\n";
  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) << "\n\n";
  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) << "\n\n";
  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) << "\n\n";

這時候,我們重新編譯代碼,就能夠看出這里面的差距了: 
這里寫圖片描述 
首先是使用默認分配器的鏈表棧速度最慢,其次是使用 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM