如何为模板类重载“new”运算符?

时间:2012-08-31 05:30:37

标签: c++ class templates overloading

我尝试在下面的模板类中重载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;
};

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是你要求的吗?

#define malloc new

MemPoolT<N> m = malloc MemPoolT<N>();

因为你那样做。