operator new

Started by
0 comments, last by BradBobak_68669 12 years, 10 months ago
Hello,

I want to use my own global allocator for my allocations. So I overloaded global operator new, which calls my global allocator:

void* operator new(size_t size, const char* desc, int line) {
void* p = MemManager::getInstance().allocate(size);
return p;
}

MemManager::allocate() can use any allocation strategy (pool, bulk, malloc() etc.)
Of course I also have to implement a corresponding global operator delete:
void operator delete(void* p) {
MemManager::getInstance().deallocate(p);
}

deallocate() frees the memory allocated by allocate(). But now comes the problem: Since I have my own global operator delete(), I also have to overwrite the global standard operator new(size_t size), even though I have no interest in changing standard operator new, because I do not use it (I only use my custom operator new with the 2 additional arguments).
How should I implement standard operator new(size_t size)? Actually I would just use malloc(), but this may not fit to my MemManager::allocate() allocation strategy and thus operator delete() will not work correctly. And if I just use my MemManager::allocate() I will allocate entities (std::string etc) that are not part of my engine with my allocator.

How could I solve this? How should I overload standard operator new(), when I have a custom operator new/delete?
Advertisement
One option is to put the new / delete inside the class that will be using it.

struct x
{
void *operator new(size_t t) { return malloc(t); }
void operator delete(void *p) { free(p); }

};


This topic is closed to new replies.

Advertisement