Sign in to follow this  
OleKaiwalker

redirect new and delete

Recommended Posts

OleKaiwalker    120
Hey, I need to help with redirecting new and delete in a rather complex manner. They ought to be redirected to my own heap mananger, a heap which needs to be allocated before use. Anyone who is willing to share some wisdom? Just an ex to help draw the picture. to allocate my heap, I do the following: heap = new Heap; but new is redirected to the heap: inline void* operator new( size_t bytes ){ return heap->alloc( bytes ); }; Trying to allocate memory for my heap, will result in a call to the not yet allocated heap.???? Hope you understand.??

Share this post


Link to post
Share on other sites
SiCrane    11839
Option 1: Don't use a standard new expression to allocate your Heap. Allocate the memory and use placement new to create the Heap. Ex:

void * heap_buffer = malloc(sizeof(Heap));
heap = new (heap_buffer) Heap;

Option 2: Use the heap as an parameter to new expressions using the heap. Ex:

void * operator new(size_t bytes, Heap * heap);

Share this post


Link to post
Share on other sites
Oxyd    1162
Third option is to define an overloaded new operator for Heap class that would do the ordinary malloc work — for Heap only. E.g.


class Heap {
public:
void* alloc(std::size_t bytes);
void free(void* mem);

void* operator new(std::size_t size);
void operator delete(void* mem);
};

void* Heap::operator new(std::size_t size) {
void* mem = std::malloc(size);
if (mem == 0) {
handle_out_of_memory();
}
return mem;
}

void Heap::operator delete(void* mem) {
if (mem == 0) {
return;
}
std::free(mem);
}

// Global ones:
void* operator new(std::size_t size) {
return heap->alloc(size);
}

void operator delete(void* mem) {
heap->free(mem);
}


Share this post


Link to post
Share on other sites
OleKaiwalker    120
Thx for the replies. If that's the only way to go about with it, I will stick with it. Esspecially with the malloc thing. However, I do recall something with undefining the standard new and something like that to get it running. But I'm not entirely sure.

Share this post


Link to post
Share on other sites
OleKaiwalker    120
Though it appears not to be the most optimal way of doing it, it seems to work.

I just throw in the following:


inline void* operator new( size_t bytes ){
if ( !heap )
return malloc( bytes );
else
return heap->malloc( bytes );
};



The objects allocated this way appear to get initialized anyway, so that kinda nice. Anyone willing to share some thoughts?

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