简体   繁体   English

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

[英]How can I overload the “new” operator for template classes?

I tried to overload the new operator in the template class below to use malloc instead of new , but I wasn't successful. 我试图在下面的模板类中重载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;
};

How can I do this? 我怎样才能做到这一点?

Is this what you're asking for? 这是您要的吗?

#define malloc new

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

Because you should not do that. 因为你不应该那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM