• Advertisement
Sign in to follow this  

redirect new and delete

This topic is 4532 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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
Sign in to follow this  

  • Advertisement