[英]How can I overload the “new” operator for template classes?
我試圖在下面的模板類中重載new
運算符,以使用malloc
而不是new
,但是我沒有成功。
template< int SIZE >
class MemPoolT : public MemPool
{
public:
MemPoolT() : root(0), currentAllocs(0), nAllocs(0), maxAllocs(0) {}
~MemPoolT()
{
for( int i=0; i<blockPtrs.Size(); ++i ) {
delete blockPtrs[i];
}
}
virtual void* Alloc()
{
if ( !root ) {
// Need a new block.
Block* block = new Block();
blockPtrs.Push( block );
for( int i=0; i<COUNT-1; ++i ) {
block->chunk[i].next = &block->chunk[i+1];
}
block->chunk[COUNT-1].next = 0;
root = block->chunk;
}
void* result = root;
root = root->next;
++currentAllocs;
if ( currentAllocs > maxAllocs ) maxAllocs = currentAllocs;
nAllocs++;
return result;
}
private:
enum { COUNT = 1024/SIZE };
union Chunk {
Chunk* next;
char mem[SIZE];
};
struct Block {
Chunk chunk[COUNT];
};
Chunk* root;
int currentAllocs;
int nAllocs;
int maxAllocs;
};
我怎樣才能做到這一點?
這是您要的嗎?
#define malloc new
MemPoolT<N> m = malloc MemPoolT<N>();
因為你不應該那樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.