Jump to content
  • Advertisement
Sign in to follow this  
3DModelerMan

Custom memory manger operator new

This topic is 1876 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

I've written a custom memory management system similar to this one http://www.gamedev.net/page/resources/_/technical/general-programming/c-custom-memory-allocation-r3010

 

Right now I'm trying to make it so that anything of a certain class has allocations and deallocations handled by that memory manager. But since operator new and operator delete are static, there's no way to keep a pointer to the allocater around so that the allocater can free whatever it allocated in the first place when delete was called. What would be the best way to hook new and delete into my memory allocater system? 

Share this post


Link to post
Share on other sites
Advertisement
You can add extra parameters to operator new, and then you can store a pointer to the allocator inside the allocation itself so that operator delete can access it:
struct Allocator
{
	int name;
	static void* Alloc( uint size  ) { return malloc(size); }
	static void  Free ( void* data ) { return free(data); }
};
class Myclass
{
	struct Block
	{
		Allocator* a;
	};
public:
	void* operator new(size_t size, Allocator& a)
	{//store the allocator pointer in a header, return the memory after the header
		Block* data = (Block*)a.Alloc(size + sizeof(Block));
		data->a = &a;
		return data+1;
	}
	void operator delete(void* memory)
	{//go back a few bytes to find the start of the header
		Block* data = ((Block*)memory)-1;
		data->a->Free( data );
	}
};

Allocator alloc = { 42 };
Myclass* object = new(alloc) Myclass;//extra parameters to new
delete object;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!