简体   繁体   English

C ++中的动态类类型

[英]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. 我正在用C ++写一个内存管理器-也就是说,一个类从堆中分配了很多字节,然后为程序使用了分配和释放函数。

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. 这将消除对转换和sizeof调用的需求,并且也将消除将对象大小传递给deallocate函数的需求。

Does anyone know of a better way I could be doing this? 有谁知道我可以做的更好的方法吗?

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

您可以为任何特定的用户定义类型重载新的运算符,并删除运算符,以便这些运算符使用您的分配器而不是默认的堆分配器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM