Memory Manager

Started by
5 comments, last by Coluna 20 years, 1 month ago
Hi; Im doing a simple memory manager, to avoid fragmentation, using a very large array of bytes and casting som portions to the struct i need. It works to structs and classes, but for inherited classes the vftable is not filled. How can i do that? is there som way to force the casting?
Advertisement
Don't try to do a simple cast. Instead allocate memory the size of the desired class and call placement new on the allocated memory. e.g.:

void * ptr = get_memory(sizeof(Object));
Object * obj = new (ptr) Object();

Just remember to explicitly call the destructor when freeing the memory.

edit: e.g.:

obj->~Object();
free_memory(ptr);

alternately override operator new() and operator delete() in classes that you use with your memory manager.

[edited by - SiCrane on March 17, 2004 4:32:01 PM]
What is this "placement new"? does it allocate some memory or only fills the vftable? do u know some good articles about overriding new and delete for individual classes? thanx
Placement new calls the constructor of the class on the memory address that you specify. In the code snippet above, you grab the memory using your custom allocator then construct the class in that memory.

I''m not sure of any good online references to overriding operator new() and operator delete() for a class. However, IIRC, the book "Effective C++" by Scott Meyers has a few items on using operator new() and operator delete() in classes.
can''t you just generally overload the new and delete operators to use your memory manager ? i never had problems with the construction of inherited classes that way...
AnubisX , can u send me any example of an overloaded new/delete of your classes? thanx
sure thing, i can even send you the memory manager code i use if you want

This topic is closed to new replies.

Advertisement