C++中高性能內(nèi)存池的實(shí)現(xiàn)詳解
一、概述
在 C/C++ 中,內(nèi)存管理是一個(gè)非常棘手的問(wèn)題,我們?cè)诰帉?xiě)一個(gè)程序的時(shí)候幾乎不可避免的要遇到內(nèi)存的分配邏輯,這時(shí)候隨之而來(lái)的有這樣一些問(wèn)題:是否有足夠的內(nèi)存可供分配?分配失敗了怎么辦? 如何管理自身的內(nèi)存使用情況? 等等一系列問(wèn)題。在一個(gè)高可用的軟件中,如果我們僅僅單純的向操作系統(tǒng)去申請(qǐng)內(nèi)存,當(dāng)出現(xiàn)內(nèi)存不足時(shí)就退出軟件,是明顯不合理的。正確的思路應(yīng)該是在內(nèi)存不足的時(shí),考慮如何管理并優(yōu)化自身已經(jīng)使用的內(nèi)存,這樣才能使得軟件變得更加可用。本次項(xiàng)目我們將實(shí)現(xiàn)一個(gè)內(nèi)存池,并使用一個(gè)棧結(jié)構(gòu)來(lái)測(cè)試我們的內(nèi)存池提供的分配性能。最終,我們要實(shí)現(xiàn)的內(nèi)存池在棧結(jié)構(gòu)中的性能,要遠(yuǎn)高于使用 std::allocator 和 std::vector,如下圖所示:
項(xiàng)目涉及的知識(shí)點(diǎn)
C++ 中的內(nèi)存分配器 std::allocator
內(nèi)存池技術(shù)
手動(dòng)實(shí)現(xiàn)模板鏈?zhǔn)綏?/p>
鏈?zhǔn)綏:土斜項(xiàng)5男阅鼙容^
內(nèi)存池簡(jiǎn)介
內(nèi)存池是池化技術(shù)中的一種形式。通常我們?cè)诰帉?xiě)程序的時(shí)候回使用 new delete 這些關(guān)鍵字來(lái)向操作系統(tǒng)申請(qǐng)內(nèi)存,而這樣造成的后果就是每次申請(qǐng)內(nèi)存和釋放內(nèi)存的時(shí)候,都需要和操作系統(tǒng)的系統(tǒng)調(diào)用打交道,從堆中分配所需的內(nèi)存。如果這樣的操作太過(guò)頻繁,就會(huì)找成大量的內(nèi)存碎片進(jìn)而降低內(nèi)存的分配性能,甚至出現(xiàn)內(nèi)存分配失敗的情況。
而內(nèi)存池就是為了解決這個(gè)問(wèn)題而產(chǎn)生的一種技術(shù)。從內(nèi)存分配的概念上看,內(nèi)存申請(qǐng)無(wú)非就是向內(nèi)存分配方索要一個(gè)指針,當(dāng)向操作系統(tǒng)申請(qǐng)內(nèi)存時(shí),
操作系統(tǒng)需要進(jìn)行復(fù)雜的內(nèi)存管理調(diào)度之后,才能正確的分配出一個(gè)相應(yīng)的指針。而這個(gè)分配的過(guò)程中,我們還面臨著分配失敗的風(fēng)險(xiǎn)。
所以,每一次進(jìn)行內(nèi)存分配,就會(huì)消耗一次分配內(nèi)存的時(shí)間,設(shè)這個(gè)時(shí)間為 T,那么進(jìn)行 n 次分配總共消耗的時(shí)間就是 nT;如果我們一開(kāi)始就確定好我們可能需要多少內(nèi)存,那么在最初的時(shí)候就分配好這樣的一塊內(nèi)存區(qū)域,當(dāng)我們需要內(nèi)存的時(shí)候,直接從這塊已經(jīng)分配好的內(nèi)存中使用即可,那么總共需要的分配時(shí)間僅僅只有 T。當(dāng) n 越大時(shí),節(jié)約的時(shí)間就越多。
二、主函數(shù)設(shè)計(jì)
我們要設(shè)計(jì)實(shí)現(xiàn)一個(gè)高性能的內(nèi)存池,那么自然避免不了需要對(duì)比已有的內(nèi)存,而比較內(nèi)存池對(duì)內(nèi)存的分配性能,就需要實(shí)現(xiàn)一個(gè)需要對(duì)內(nèi)存進(jìn)行動(dòng)態(tài)分配的結(jié)構(gòu)(比如:鏈表?xiàng)#?,為此,可以?xiě)出如下的代碼:
#include <iostream> // std::cout, std::endl #include <cassert> // assert() #include <ctime> // clock() #include <vector> // std::vector #include "MemoryPool.hpp" // MemoryPool<T> #include "StackAlloc.hpp" // StackAlloc<T, Alloc> // 插入元素個(gè)數(shù) #define ELEMS 10000000 // 重復(fù)次數(shù) #define REPS 100 int main() { clock_t start; // 使用 STL 默認(rèn)分配器 StackAlloc<int, std::allocator<int> > stackDefault; start = clock(); for (int j = 0; j < REPS; j++) { assert(stackDefault.empty()); for (int i = 0; i < ELEMS; i++) stackDefault.push(i); for (int i = 0; i < ELEMS; i++) stackDefault.pop(); } std::cout << "Default Allocator Time: "; std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "\n\n"; // 使用內(nèi)存池 StackAlloc<int, MemoryPool<int> > stackPool; start = clock(); for (int j = 0; j < REPS; j++) { assert(stackPool.empty()); for (int i = 0; i < ELEMS; i++) stackPool.push(i); for (int i = 0; i < ELEMS; i++) stackPool.pop(); } std::cout << "MemoryPool Allocator Time: "; std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "\n\n"; return 0; }
在上面的兩段代碼中,StackAlloc 是一個(gè)鏈表?xiàng)?,接受兩個(gè)模板參數(shù),第一個(gè)參數(shù)是棧中的元素類(lèi)型,第二個(gè)參數(shù)就是棧使用的內(nèi)存分配器。
因此,這個(gè)內(nèi)存分配器的模板參數(shù)就是整個(gè)比較過(guò)程中唯一的變量,使用默認(rèn)分配器的模板參數(shù)為 std::allocator,而使用內(nèi)存池的模板參數(shù)為 MemoryPool。
std::allocator 是 C++標(biāo)準(zhǔn)庫(kù)中提供的默認(rèn)分配器,他的特點(diǎn)就在于我們?cè)?使用 new 來(lái)申請(qǐng)內(nèi)存構(gòu)造新對(duì)象的時(shí)候,勢(shì)必要調(diào)用類(lèi)對(duì)象的默認(rèn)構(gòu)造函數(shù),而使用 std::allocator 則可以將內(nèi)存分配和對(duì)象的構(gòu)造這兩部分邏輯給分離開(kāi)來(lái),使得分配的內(nèi)存是原始、未構(gòu)造的。
下面我們來(lái)實(shí)現(xiàn)這個(gè)鏈表?xiàng)!?/p>
三、模板鏈表?xiàng)?/h2>
棧的結(jié)構(gòu)非常的簡(jiǎn)單,沒(méi)有什么復(fù)雜的邏輯操作,其成員函數(shù)只需要考慮兩個(gè)基本的操作:入棧、出棧。為了操作上的方便,我們可能還需要這樣一些方法:判斷棧是否空、清空棧、獲得棧頂元素。
#include <memory> template <typename T> struct StackNode_ { T data; StackNode_* prev; }; // T 為存儲(chǔ)的對(duì)象類(lèi)型, Alloc 為使用的分配器, 并默認(rèn)使用 std::allocator 作為對(duì)象的分配器 template <typename T, typename Alloc = std::allocator<T> > class StackAlloc { public: // 使用 typedef 簡(jiǎn)化類(lèi)型名 typedef StackNode_<T> Node; typedef typename Alloc::template rebind<Node>::other allocator; // 默認(rèn)構(gòu)造 StackAlloc() { head_ = 0; } // 默認(rèn)析構(gòu) ~StackAlloc() { clear(); } // 當(dāng)棧中元素為空時(shí)返回 true bool empty() {return (head_ == 0);} // 釋放棧中元素的所有內(nèi)存 void clear(); // 壓棧 void push(T element); // 出棧 T pop(); // 返回棧頂元素 T top() { return (head_->data); } private: // allocator allocator_; // 棧頂 Node* head_; };
簡(jiǎn)單的邏輯諸如構(gòu)造、析構(gòu)、判斷棧是否空、返回棧頂元素的邏輯都非常簡(jiǎn)單,直接在上面的定義中實(shí)現(xiàn)了,下面我們來(lái)實(shí)現(xiàn) clear(), push() 和 pop() 這三個(gè)重要的邏輯:
// 釋放棧中元素的所有內(nèi)存 void clear() { Node* curr = head_; // 依次出棧 while (curr != 0) { Node* tmp = curr->prev; // 先析構(gòu), 再回收內(nèi)存 allocator_.destroy(curr); allocator_.deallocate(curr, 1); curr = tmp; } head_ = 0; } // 入棧 void push(T element) { // 為一個(gè)節(jié)點(diǎn)分配內(nèi)存 Node* newNode = allocator_.allocate(1); // 調(diào)用節(jié)點(diǎn)的構(gòu)造函數(shù) allocator_.construct(newNode, Node()); // 入棧操作 newNode->data = element; newNode->prev = head_; head_ = newNode; } // 出棧 T pop() { // 出棧操作 返回出棧元素 T result = head_->data; Node* tmp = head_->prev; allocator_.destroy(head_); allocator_.deallocate(head_, 1); head_ = tmp; return result; }
至此,我們完成了整個(gè)模板鏈表?xiàng)?,現(xiàn)在我們可以先注釋掉 main() 函數(shù)中使用內(nèi)存池部分的代碼來(lái)測(cè)試這個(gè)連表?xiàng)5膬?nèi)存分配情況,我們就能夠得到這樣的結(jié)果:
在使用 std::allocator 的默認(rèn)內(nèi)存分配器中,在
#define ELEMS 10000000 #define REPS 100
的條件下,總共花費(fèi)了近一分鐘的時(shí)間。
如果覺(jué)得花費(fèi)的時(shí)間較長(zhǎng),不愿等待,則你嘗試可以減小這兩個(gè)值
總結(jié)
本節(jié)我們實(shí)現(xiàn)了一個(gè)用于測(cè)試性能比較的模板鏈表?xiàng)#壳暗拇a如下。在下一節(jié)中,我們開(kāi)始詳細(xì)實(shí)現(xiàn)我們的高性能內(nèi)存池。
// StackAlloc.hpp #ifndef STACK_ALLOC_H #define STACK_ALLOC_H #include <memory> template <typename T> struct StackNode_ { T data; StackNode_* prev; }; // T 為存儲(chǔ)的對(duì)象類(lèi)型, Alloc 為使用的分配器, // 并默認(rèn)使用 std::allocator 作為對(duì)象的分配器 template <class T, class Alloc = std::allocator<T> > class StackAlloc { public: // 使用 typedef 簡(jiǎn)化類(lèi)型名 typedef StackNode_<T> Node; typedef typename Alloc::template rebind<Node>::other allocator; // 默認(rèn)構(gòu)造 StackAlloc() { head_ = 0; } // 默認(rèn)析構(gòu) ~StackAlloc() { clear(); } // 當(dāng)棧中元素為空時(shí)返回 true bool empty() {return (head_ == 0);} // 釋放棧中元素的所有內(nèi)存 void clear() { Node* curr = head_; while (curr != 0) { Node* tmp = curr->prev; allocator_.destroy(curr); allocator_.deallocate(curr, 1); curr = tmp; } head_ = 0; } // 入棧 void push(T element) { // 為一個(gè)節(jié)點(diǎn)分配內(nèi)存 Node* newNode = allocator_.allocate(1); // 調(diào)用節(jié)點(diǎn)的構(gòu)造函數(shù) allocator_.construct(newNode, Node()); // 入棧操作 newNode->data = element; newNode->prev = head_; head_ = newNode; } // 出棧 T pop() { // 出棧操作 返回出棧結(jié)果 T result = head_->data; Node* tmp = head_->prev; allocator_.destroy(head_); allocator_.deallocate(head_, 1); head_ = tmp; return result; } // 返回棧頂元素 T top() { return (head_->data); } private: allocator allocator_; Node* head_; }; #endif // STACK_ALLOC_H
// main.cpp #include <iostream> #include <cassert> #include <ctime> #include <vector> // #include "MemoryPool.hpp" #include "StackAlloc.hpp" // 根據(jù)電腦性能調(diào)整這些值 // 插入元素個(gè)數(shù) #define ELEMS 25000000 // 重復(fù)次數(shù) #define REPS 50 int main() { clock_t start; // 使用默認(rèn)分配器 StackAlloc<int, std::allocator<int> > stackDefault; start = clock(); for (int j = 0; j < REPS; j++) { assert(stackDefault.empty()); for (int i = 0; i < ELEMS; i++) stackDefault.push(i); for (int i = 0; i < ELEMS; i++) stackDefault.pop(); } std::cout << "Default Allocator Time: "; std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "\n\n"; // 使用內(nèi)存池 // StackAlloc<int, MemoryPool<int> > stackPool; // start = clock(); // for (int j = 0; j < REPS; j++) { // assert(stackPool.empty()); // for (int i = 0; i < ELEMS; i++) // stackPool.push(i); // for (int i = 0; i < ELEMS; i++) // stackPool.pop(); // } // std::cout << "MemoryPool Allocator Time: "; // std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "\n\n"; return 0; }
四、設(shè)計(jì)內(nèi)存池
在上一節(jié)實(shí)驗(yàn)中,我們?cè)谀0彐湵項(xiàng)V惺褂昧四J(rèn)構(gòu)造器來(lái)管理?xiàng)2僮髦械脑貎?nèi)存,一共涉及到了 rebind::other, allocate(), dealocate(), construct(), destroy()這些關(guān)鍵性的接口。所以為了讓代碼直接可用,我們同樣應(yīng)該在內(nèi)存池中設(shè)計(jì)同樣的接口:
#ifndef MEMORY_POOL_HPP #define MEMORY_POOL_HPP #include <climits> #include <cstddef> template <typename T, size_t BlockSize = 4096> class MemoryPool { public: // 使用 typedef 簡(jiǎn)化類(lèi)型書(shū)寫(xiě) typedef T* pointer; // 定義 rebind<U>::other 接口 template <typename U> struct rebind { typedef MemoryPool<U> other; }; // 默認(rèn)構(gòu)造, 初始化所有的槽指針 // C++11 使用了 noexcept 來(lái)顯式的聲明此函數(shù)不會(huì)拋出異常 MemoryPool() noexcept { currentBlock_ = nullptr; currentSlot_ = nullptr; lastSlot_ = nullptr; freeSlots_ = nullptr; } // 銷(xiāo)毀一個(gè)現(xiàn)有的內(nèi)存池 ~MemoryPool() noexcept; // 同一時(shí)間只能分配一個(gè)對(duì)象, n 和 hint 會(huì)被忽略 pointer allocate(size_t n = 1, const T* hint = 0); // 銷(xiāo)毀指針 p 指向的內(nèi)存區(qū)塊 void deallocate(pointer p, size_t n = 1); // 調(diào)用構(gòu)造函數(shù) template <typename U, typename... Args> void construct(U* p, Args&&... args); // 銷(xiāo)毀內(nèi)存池中的對(duì)象, 即調(diào)用對(duì)象的析構(gòu)函數(shù) template <typename U> void destroy(U* p) { p->~U(); } ??????? private: // 用于存儲(chǔ)內(nèi)存池中的對(duì)象槽, // 要么被實(shí)例化為一個(gè)存放對(duì)象的槽, // 要么被實(shí)例化為一個(gè)指向存放對(duì)象槽的槽指針 union Slot_ { T element; Slot_* next; }; // 數(shù)據(jù)指針 typedef char* data_pointer_; // 對(duì)象槽 typedef Slot_ slot_type_; // 對(duì)象槽指針 typedef Slot_* slot_pointer_; // 指向當(dāng)前內(nèi)存區(qū)塊 slot_pointer_ currentBlock_; // 指向當(dāng)前內(nèi)存區(qū)塊的一個(gè)對(duì)象槽 slot_pointer_ currentSlot_; // 指向當(dāng)前內(nèi)存區(qū)塊的最后一個(gè)對(duì)象槽 slot_pointer_ lastSlot_; // 指向當(dāng)前內(nèi)存區(qū)塊中的空閑對(duì)象槽 slot_pointer_ freeSlots_; // 檢查定義的內(nèi)存池大小是否過(guò)小 static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small."); }; #endif // MEMORY_POOL_HPP
在上面的類(lèi)設(shè)計(jì)中可以看到,在這個(gè)內(nèi)存池中,其實(shí)是使用鏈表來(lái)管理整個(gè)內(nèi)存池的內(nèi)存區(qū)塊的。內(nèi)存池首先會(huì)定義固定大小的基本內(nèi)存區(qū)塊(Block),然后在其中定義了一個(gè)可以實(shí)例化為存放對(duì)象內(nèi)存槽的對(duì)象槽(Slot_)和對(duì)象槽指針的一個(gè)聯(lián)合。然后在區(qū)塊中,定義了四個(gè)關(guān)鍵性質(zhì)的指針,它們的作用分別是:
currentBlock_: 指向當(dāng)前內(nèi)存區(qū)塊的指針
currentSlot_: 指向當(dāng)前內(nèi)存區(qū)塊中的對(duì)象槽
lastSlot_: 指向當(dāng)前內(nèi)存區(qū)塊中的最后一個(gè)對(duì)象槽
freeSlots_: 指向當(dāng)前內(nèi)存區(qū)塊中所有空閑的對(duì)象槽
梳理好整個(gè)內(nèi)存池的設(shè)計(jì)結(jié)構(gòu)之后,我們就可以開(kāi)始實(shí)現(xiàn)關(guān)鍵性的邏輯了。
五、實(shí)現(xiàn)
MemoryPool::construct() 實(shí)現(xiàn)
MemoryPool::construct() 的邏輯是最簡(jiǎn)單的,我們需要實(shí)現(xiàn)的,僅僅只是調(diào)用信件對(duì)象的構(gòu)造函數(shù)即可,因此:
// 調(diào)用構(gòu)造函數(shù), 使用 std::forward 轉(zhuǎn)發(fā)變參模板 template <typename U, typename... Args> void construct(U* p, Args&&... args) { new (p) U (std::forward<Args>(args)...); }
MemoryPool::deallocate() 實(shí)現(xiàn)
MemoryPool::deallocate() 是在對(duì)象槽中的對(duì)象被析構(gòu)后才會(huì)被調(diào)用的,主要目的是銷(xiāo)毀內(nèi)存槽。其邏輯也不復(fù)雜:
// 銷(xiāo)毀指針 p 指向的內(nèi)存區(qū)塊 void deallocate(pointer p, size_t n = 1) { if (p != nullptr) { // reinterpret_cast 是強(qiáng)制類(lèi)型轉(zhuǎn)換符 // 要訪(fǎng)問(wèn) next 必須強(qiáng)制將 p 轉(zhuǎn)成 slot_pointer_ reinterpret_cast<slot_pointer_>(p)->next = freeSlots_; freeSlots_ = reinterpret_cast<slot_pointer_>(p); } }
MemoryPool::~MemoryPool() 實(shí)現(xiàn)
析構(gòu)函數(shù)負(fù)責(zé)銷(xiāo)毀整個(gè)內(nèi)存池,因此我們需要逐個(gè)刪除掉最初向操作系統(tǒng)申請(qǐng)的內(nèi)存塊:
????// 銷(xiāo)毀一個(gè)現(xiàn)有的內(nèi)存池 ~MemoryPool() noexcept { // 循環(huán)銷(xiāo)毀內(nèi)存池中分配的內(nèi)存區(qū)塊 slot_pointer_ curr = currentBlock_; while (curr != nullptr) { slot_pointer_ prev = curr->next; operator delete(reinterpret_cast<void*>(curr)); curr = prev; } }
MemoryPool::allocate() 實(shí)現(xiàn)
MemoryPool::allocate() 毫無(wú)疑問(wèn)是整個(gè)內(nèi)存池的關(guān)鍵所在,但實(shí)際上理清了整個(gè)內(nèi)存池的設(shè)計(jì)之后,其實(shí)現(xiàn)并不復(fù)雜。具體實(shí)現(xiàn)如下:
????// 同一時(shí)間只能分配一個(gè)對(duì)象, n 和 hint 會(huì)被忽略 pointer allocate(size_t n = 1, const T* hint = 0) { // 如果有空閑的對(duì)象槽,那么直接將空閑區(qū)域交付出去 if (freeSlots_ != nullptr) { pointer result = reinterpret_cast<pointer>(freeSlots_); freeSlots_ = freeSlots_->next; return result; } else { // 如果對(duì)象槽不夠用了,則分配一個(gè)新的內(nèi)存區(qū)塊 if (currentSlot_ >= lastSlot_) { // 分配一個(gè)新的內(nèi)存區(qū)塊,并指向前一個(gè)內(nèi)存區(qū)塊 data_pointer_ newBlock = reinterpret_cast<data_pointer_>(operator new(BlockSize)); reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_; currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock); // 填補(bǔ)整個(gè)區(qū)塊來(lái)滿(mǎn)足元素內(nèi)存區(qū)域的對(duì)齊要求 data_pointer_ body = newBlock + sizeof(slot_pointer_); uintptr_t result = reinterpret_cast<uintptr_t>(body); size_t bodyPadding = (alignof(slot_type_) - result) % alignof(slot_type_); currentSlot_ = reinterpret_cast<slot_pointer_>(body + bodyPadding); lastSlot_ = reinterpret_cast<slot_pointer_>(newBlock + BlockSize - sizeof(slot_type_) + 1); } return reinterpret_cast<pointer>(currentSlot_++); } }
六、與 std::vector 的性能對(duì)比
我們知道,對(duì)于棧來(lái)說(shuō),鏈棧其實(shí)并不是最好的實(shí)現(xiàn)方式,因?yàn)檫@種結(jié)構(gòu)的棧不可避免的會(huì)涉及到指針相關(guān)的操作,同時(shí),還會(huì)消耗一定量的空間來(lái)存放節(jié)點(diǎn)之間的指針。事實(shí)上,我們可以使用 std::vector 中的 push_back() 和 pop_back() 這兩個(gè)操作來(lái)模擬一個(gè)棧,我們不妨來(lái)對(duì)比一下這個(gè) std::vector 與我們所實(shí)現(xiàn)的內(nèi)存池在性能上誰(shuí)高誰(shuí)低,我們?cè)?主函數(shù)中加入如下代碼:
// 比較內(nèi)存池和 std::vector 之間的性能 std::vector<int> stackVector; start = clock(); for (int j = 0; j < REPS; j++) { assert(stackVector.empty()); for (int i = 0; i < ELEMS; i++) stackVector.push_back(i); for (int i = 0; i < ELEMS; i++) stackVector.pop_back(); } std::cout << "Vector Time: "; std::cout << (((double)clock() - start) / CLOCKS_PER_SEC) << "\n\n";
這時(shí)候,我們重新編譯代碼,就能夠看出這里面的差距了:
首先是使用默認(rèn)分配器的鏈表?xiàng)K俣茸盥浯问鞘褂?std::vector 模擬的棧結(jié)構(gòu),在鏈表?xiàng)5幕A(chǔ)上大幅度削減了時(shí)間。
std::vector 的實(shí)現(xiàn)方式其實(shí)和內(nèi)存池較為類(lèi)似,在 std::vector 空間不夠用時(shí),會(huì)拋棄現(xiàn)在的內(nèi)存區(qū)域重新申請(qǐng)一塊更大的區(qū)域,并將現(xiàn)在內(nèi)存區(qū)域中的數(shù)據(jù)整體拷貝一份到新區(qū)域中。
最后,對(duì)于我們實(shí)現(xiàn)的內(nèi)存池,消耗的時(shí)間最少,即內(nèi)存分配性能最佳,完成了本項(xiàng)目。
總結(jié)
本節(jié)中,我們實(shí)現(xiàn)了我們上節(jié)實(shí)驗(yàn)中未實(shí)現(xiàn)的內(nèi)存池,完成了整個(gè)項(xiàng)目的目標(biāo)。這個(gè)內(nèi)存池不僅精簡(jiǎn)而且高效,整個(gè)內(nèi)存池的完整代碼如下:
#ifndef MEMORY_POOL_HPP #define MEMORY_POOL_HPP #include <climits> #include <cstddef> template <typename T, size_t BlockSize = 4096> class MemoryPool { public: // 使用 typedef 簡(jiǎn)化類(lèi)型書(shū)寫(xiě) typedef T* pointer; // 定義 rebind<U>::other 接口 template <typename U> struct rebind { typedef MemoryPool<U> other; }; // 默認(rèn)構(gòu)造 // C++11 使用了 noexcept 來(lái)顯式的聲明此函數(shù)不會(huì)拋出異常 MemoryPool() noexcept { currentBlock_ = nullptr; currentSlot_ = nullptr; lastSlot_ = nullptr; freeSlots_ = nullptr; } // 銷(xiāo)毀一個(gè)現(xiàn)有的內(nèi)存池 ~MemoryPool() noexcept { // 循環(huán)銷(xiāo)毀內(nèi)存池中分配的內(nèi)存區(qū)塊 slot_pointer_ curr = currentBlock_; while (curr != nullptr) { slot_pointer_ prev = curr->next; operator delete(reinterpret_cast<void*>(curr)); curr = prev; } } // 同一時(shí)間只能分配一個(gè)對(duì)象, n 和 hint 會(huì)被忽略 pointer allocate(size_t n = 1, const T* hint = 0) { if (freeSlots_ != nullptr) { pointer result = reinterpret_cast<pointer>(freeSlots_); freeSlots_ = freeSlots_->next; return result; } else { if (currentSlot_ >= lastSlot_) { // 分配一個(gè)內(nèi)存區(qū)塊 data_pointer_ newBlock = reinterpret_cast<data_pointer_>(operator new(BlockSize)); reinterpret_cast<slot_pointer_>(newBlock)->next = currentBlock_; currentBlock_ = reinterpret_cast<slot_pointer_>(newBlock); data_pointer_ body = newBlock + sizeof(slot_pointer_); uintptr_t result = reinterpret_cast<uintptr_t>(body); size_t bodyPadding = (alignof(slot_type_) - result) % alignof(slot_type_); currentSlot_ = reinterpret_cast<slot_pointer_>(body + bodyPadding); lastSlot_ = reinterpret_cast<slot_pointer_>(newBlock + BlockSize - sizeof(slot_type_) + 1); } return reinterpret_cast<pointer>(currentSlot_++); } } // 銷(xiāo)毀指針 p 指向的內(nèi)存區(qū)塊 void deallocate(pointer p, size_t n = 1) { if (p != nullptr) { reinterpret_cast<slot_pointer_>(p)->next = freeSlots_; freeSlots_ = reinterpret_cast<slot_pointer_>(p); } } // 調(diào)用構(gòu)造函數(shù), 使用 std::forward 轉(zhuǎn)發(fā)變參模板 template <typename U, typename... Args> void construct(U* p, Args&&... args) { new (p) U (std::forward<Args>(args)...); } // 銷(xiāo)毀內(nèi)存池中的對(duì)象, 即調(diào)用對(duì)象的析構(gòu)函數(shù) template <typename U> void destroy(U* p) { p->~U(); } private: // 用于存儲(chǔ)內(nèi)存池中的對(duì)象槽 union Slot_ { T element; Slot_* next; }; // 數(shù)據(jù)指針 typedef char* data_pointer_; // 對(duì)象槽 typedef Slot_ slot_type_; // 對(duì)象槽指針 typedef Slot_* slot_pointer_; // 指向當(dāng)前內(nèi)存區(qū)塊 slot_pointer_ currentBlock_; // 指向當(dāng)前內(nèi)存區(qū)塊的一個(gè)對(duì)象槽 slot_pointer_ currentSlot_; // 指向當(dāng)前內(nèi)存區(qū)塊的最后一個(gè)對(duì)象槽 slot_pointer_ lastSlot_; // 指向當(dāng)前內(nèi)存區(qū)塊中的空閑對(duì)象槽 slot_pointer_ freeSlots_; // 檢查定義的內(nèi)存池大小是否過(guò)小 static_assert(BlockSize >= 2 * sizeof(slot_type_), "BlockSize too small."); }; #endif // MEMORY_POOL_HPP
以上就是C++中高性能內(nèi)存池的實(shí)現(xiàn)詳解的詳細(xì)內(nèi)容,更多關(guān)于C++高性能內(nèi)存池的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C語(yǔ)言數(shù)據(jù)結(jié)構(gòu)之vector底層實(shí)現(xiàn)機(jī)制解析
向量(Vector)是一個(gè)封裝了動(dòng)態(tài)大小數(shù)組的順序容器(Sequence?Container)。跟任意其它類(lèi)型容器一樣,它能夠存放各種類(lèi)型的對(duì)象??梢院?jiǎn)單的認(rèn)為,向量是一個(gè)能夠存放任意類(lèi)型的動(dòng)態(tài)數(shù)組2021-11-11C語(yǔ)言 typedef:給類(lèi)型起一個(gè)別名
本文主要介紹C語(yǔ)言 typedef,這里整理了相關(guān)資料及簡(jiǎn)單示例代碼幫助大家學(xué)習(xí)理解,有興趣的小伙伴可以參考下2016-08-08Visual Studio 2019 DLL動(dòng)態(tài)庫(kù)連接實(shí)例(圖文教程)
這篇文章主要介紹了Visual Studio 2019 DLL動(dòng)態(tài)庫(kù)連接實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03C++中進(jìn)行txt文件讀入和寫(xiě)入的方法示例
這篇文章主要給大家介紹了C++中進(jìn)行txt文件讀入和寫(xiě)入的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C++具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09C語(yǔ)言實(shí)現(xiàn)紙牌游戲之小貓釣魚(yú)算法
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)紙牌游戲之小貓釣魚(yú)算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01關(guān)于C++多重繼承下虛表結(jié)構(gòu)的問(wèn)題
這篇文章主要介紹了C++ 多重繼承下虛表結(jié)構(gòu)的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09C語(yǔ)言編程中對(duì)目錄進(jìn)行基本的打開(kāi)關(guān)閉和讀取操作詳解
這篇文章主要介紹了C語(yǔ)言編程中對(duì)目錄進(jìn)行基本的打開(kāi)關(guān)閉和讀取操作,是C語(yǔ)言入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09