Jump to content

View more

Image of the Day

「筋肉兄貴のスーパーラン!」
兄貴に立ちはだかるダンボール・・・(´・ω・`)
ムズい・・激ムズって感じにそろそろ変わってきます。
(o・ω・o)
 #indiedev  #indiegame #screenshotsaturday https://t.co/xKIzRQMdHm
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net's newsletters to receive the latest updates and exclusive content.


Sign up now

Custom memory manger operator new

2: Adsense

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
2 replies to this topic

#1 3DModelerMan   Members   

1173
Like
0Likes
Like

Posted 30 April 2013 - 07:54 PM

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? 



#2 Hodgman   Moderators   

50361
Like
3Likes
Like

Posted 30 April 2013 - 09:46 PM

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;


#3 3DModelerMan   Members   

1173
Like
0Likes
Like

Posted 01 May 2013 - 07:56 AM

Thanks. That should work perfect.






Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.