Sign in to follow this  
schupf

operator new

Recommended Posts

schupf    221
Hello,

I want to use my own global allocator for my allocations. So I overloaded global operator new, which calls my global allocator:
[code]
void* operator new(size_t size, const char* desc, int line) {
void* p = MemManager::getInstance().allocate(size);
return p;
}
[/code]
MemManager::allocate() can use any allocation strategy (pool, bulk, malloc() etc.)
Of course I also have to implement a corresponding global operator delete:
[code]void operator delete(void* p) {
MemManager::getInstance().deallocate(p);
}[/code]
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?

Share this post


Link to post
Share on other sites
One option is to put the new / delete inside the class that will be using it.
[code]
struct x
{
void *operator new(size_t t) { return malloc(t); }
void operator delete(void *p) { free(p); }

};


[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this