0

I'm writing a memory manager in C++ - that is, a class that allocates a lot of bytes from the heap, and then has allocate and deallocate functions for my program to use.

void* allocate(int size);
void deallocate(void*, int size);

This works fine, but what I don't like about it is that I need to do this to use it:

CClass* myobject = (CClass*) manager->allocate(sizeof(CClass));

So me question is, is there a way to pass the class type to the functions rather than using void pointers? This would remove the need for casting and the sizeof call, and it may also remove the need to pass the object size to the deallocate function.

Does anyone know of a better way I could be doing this?

2
  • 1
    templates ftw. BTW Do these classes have constructors and destructors? Commented Dec 13, 2013 at 12:12
  • You mean CClass? Its constructor and destructor won't be called when I use this method, I realise that. Commented Dec 13, 2013 at 12:21

2 Answers 2

5

You could use template functions.

Simplified example:

#include <string>
#include <iostream>
using namespace std;

template<typename T>
T* allocate() {
  return (T*) malloc(sizeof(T));
}

int main() {
  int *s = allocate<int>();
  *s = 42;
  return *s;
}
Sign up to request clarification or add additional context in comments.
0

You can overload operator new, and operator delete for any specific user-defined type so that those operators use your allocator instead of the default heap allocator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.