views:

90

answers:

2

Imagine I'm in C-land, and I have

 void* my_alloc(size_t size);
 void* my_free(void*);

then I can go through my code and replace all calls to malloc/free with my_alloc/my_free.

How, I know that given a class Foo, I can do placement new; I can also overload the new operator. However, is there a way to do this for all my C++ classes? (i.e. I want to use my own allocator for new and new[]; but I don't want to run through and hack every class I have defined.)

Thanks!

+7  A: 

In global scope,

 void* operator new(size_t s) { return my_alloc(s); }
 void operator delete(void* p) { my_free(p); }
 void* operator new[](size_t s) { return my_alloc(s); }
 void operator delete[](void* p) { my_free(p); }
KennyTM
+1 for also mentioning the array new/delete
digitalarbeiter
actually, there are 12 functions to replace: new/delete, new/delete nothrow, placement new/delete - and each with an array version. See here: http://www.gamedev.net/community/forums/viewreply.asp?ID=2471345
Tobias Langner
@Tobias Good point about the nothrow versions, but the placement operators don't need replacing
James Hopkin
Note: this approach will only replace new/delete *in your own code*.new/delete calls in statically-linked dependencies will not be modified.
Computer Guru
@James: May I ask why? I think I read that you must not forget placement new in case someone uses it.
Tobias Langner
@Tobias: You *cannot* replace placement-new. Think about what the function does and you'll understand why. (Hint: Nothing!)
GMan
Thank you, of course you are right.
Tobias Langner
+2  A: 

Define custom global new and delete operator functions :

void* operator new(size_t size) 
{
    //do something
    return malloc(size);
}

void operator delete(void *p) 
{
    //do something     
     free(p); 
}

Placement new can be used when you want to create object from the pre-allocated buffer.

Frequent use of new and delete will cause memory fregmentation and it costs to memory access and allocation.So the whole idea of placement new is to create memory pool at the program start and destroy it at program end and all request for memory just returns free memory location from the pool.

Ashish
This is a replacement of the new operator, not 'placement new': http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10
James Hopkin
I know that both are different.Ok i have removed the confusion and removed "Thus" word.
Ashish