我正在实现一个简单的MemPool。 MemPool以LinkList的形式实现。但是我不知道要声明
static Node * free_mem_head;
正确。
template <int PIECE_SIZE>
class mempool {
private:
struct Node {
Node * next;
char p_mem[PIECE_SIZE];
};
const static size_t bunch_size = 50;
public:
static Node * free_mem_head;
mempool();
~mempool();
void * allocate();
void deallocate(void *);
};
template <int PIECE_SIZE>
mempool<PIECE_SIZE>::mempool() {}
template <int PIECE_SIZE>
mempool<PIECE_SIZE>::~mempool() {
}
template <int PIECE_SIZE>
void* mempool<PIECE_SIZE>::allocate() {
if (free_mem_head == NULL) {
size_t size_to_new = bunch_size * sizeof(Node);
void *new_mem = ::operator new(size_to_new);
free_mem_head = static_cast<Node*>(new_mem);
for (int i = 0; i<bunch_size - 1; i++) {
free_mem_head[i].next = &free_mem_head[i + 1];
}
free_mem_head[bunch_size - 1].next = NULL;
Node *res = free_mem_head;
free_mem_head = free_mem_head->next;
}
else {
Node * res = free_mem_head;
free_mem_head = free_mem_head->next;
return res;
}
}
template <int PIECE_SIZE>
void mempool<PIECE_SIZE>::deallocate(void * node_to_free) {
Node * p = static_cast<Node*> (node_to_free);
p->next = free_mem_head;
p = free_mem_head;
}
这是我的用法:
#include <cstring>
class Test {
public:
Test(int a, int b) :a(a), b(b) {
strncpy(c, "abc", 3);
c[3] = 0;
}
int a;
double b;
char c[100];
private:
void *operator new(size_t s1);
void operator delete(void *);
};
和
class Node;
mempool<sizeof(Test)> mempool1;
Node * mempool<sizeof(Test)>::free_mem_head = NULL;
void * Test::operator new(size_t s1) {
return mempool1.allocate();
}
void Test::operator delete(void *p) {
mempool1.deallocate(p);
return;
}
出现编译错误: 错误:专用成员“ mempool <120> :: free_mem_head”需要使用“ template <>”语法 节点* mempool :: free_mem_head = NULL;
答案 0 :(得分:4)
您应定义free_mem_head
而不进行专门化:
template<int PIECE_SIZE>
typename mempool<PIECE_SIZE>::Node * mempool<PIECE_SIZE>::free_mem_head{};
使用C ++ 17可以在模板本身内部进行定义:
static inline Node * free_mem_head{};