user2226001
user2226001

Reputation: 99

Dynamic class type in C++

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?

Upvotes: 0

Views: 185

Answers (2)

YoungJohn
YoungJohn

Reputation: 956

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.

Upvotes: 0

Vlad
Vlad

Reputation: 18643

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;
}

Upvotes: 5

Related Questions