Created
September 24, 2015 15:29
-
-
Save loosechainsaw/aca6ffd32aa3c60f696b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
template<typename T, size_t N> | |
class MemoryPool{ | |
struct node{ | |
node* next; | |
}; | |
union payload{ | |
T data; | |
node* element; | |
}; | |
public: | |
MemoryPool() : block{ ::operator new(sizeof(payload) * N)}, next{block}, used{0}, head{nullptr} | |
{ | |
} | |
template<typename... Args> | |
T* allocate(Args&&... args){ | |
cout << "Allocating: " << next << endl; | |
void* address = nullptr; | |
if(head == nullptr) { | |
address = next; | |
next = (char*)(address) + sizeof(payload); | |
used++; | |
} | |
else{ | |
address = head; | |
head = head->next; | |
} | |
new(address) T(std::forward<Args>(args)...); | |
cout << "Used: " << used << endl; | |
cout << "Next at: " << next << endl; | |
return (T*) address; | |
} | |
void deallocate(void* entity){ | |
cout << "Deallocating: " << entity << endl; | |
memset(entity,0, sizeof(payload)); | |
node* phead = head; | |
head = (node*) entity; | |
head->next = phead; | |
} | |
~MemoryPool(){ | |
cout << "Deleting block: " << block << endl; | |
::operator delete(block); | |
} | |
private: | |
void* block; | |
void* next; | |
size_t used; | |
node* head; | |
}; | |
struct X{ | |
X(int vv) : v{vv}{} | |
int v; | |
}; | |
int main() { | |
MemoryPool<X,1000> memory_pool; | |
vector<X*> v; | |
for(int i = 0; i < 50; ++i){ | |
v.push_back(memory_pool.allocate(i)); | |
} | |
auto a = v[49]; | |
auto b = v[48]; | |
v.resize(48); | |
v.shrink_to_fit(); | |
memory_pool.deallocate(a); | |
memory_pool.deallocate(b); | |
v.push_back(memory_pool.allocate(600)); | |
v.push_back(memory_pool.allocate(200)); | |
for(auto i = v.begin(); i != v.end(); ++i) | |
cout << (*i)->v << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment