我正在使用模板化内存池,它使用以下 union 来存储数据:
union MemoryPoolNode
{
MemoryPoolNode *next;
T data;
};
之前,我使用 malloc 为新节点分配内存:
MemoryPoolNode *node = (MemoryPoolNode*)malloc(sizeof(MemoryPoolNode));
并释放它:
free(node);
现在,我想用 new 和 delete 替换对 malloc 和 free 的调用。
为此,要为节点分配内存,我现在正在执行以下操作:
MemoryPoolNode *node = (MemoryPoolNode*)new char[sizeof(MemoryPoolNode)];
并释放它:
char *toDelete = (char*)node;
delete[] toDelete;
这是正确的做法吗?
我的 union 中的类型 T 可以是具有构造函数和析构函数的类,当我为内存池中的新节点分配内存时,我不希望调用构造函数或析构函数,因为我已经使用了放置new ,每次弹出节点并将其放回内存池时,我都会手动调用析构函数,因此我只想分配和释放内存,就像 malloc 和 free 一样。
仅供引用,我正在替换 malloc 和 free,因为池使用的环境中可以覆盖“new”和“delete”以相应地分配内存(用户空间、内核等)。
最佳答案
您的代码已损坏,您需要先修复它。
C++11 之前版本:
Unions cannot contain a non-static data member with a non-trivial special member function (copy constructor, copy-assignment operator, or destructor).
后 C++11:
If a union contains a non-static data member with a non-trivial special member function (default constructor, copy/move constructor, copy/move assignment, or destructor), that function is deleted by default in the union and needs to be defined explicitly by the programmer.
参见here 。你不遵守任何一条规则。您需要解决这个问题。
一旦修复它,您只需使用node = new MemoryPoolNode()
和delete node;
即可。
对于 C++11,这样做:
union MemoryPoolNode
{
MemoryPoolNode *next;
T data;
MemoryPoolNode() : next(NULL) { ; }
~MemoryPoolNode() { ; }
};
关于c++ - 将内存池中的malloc和free替换为new和delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38786590/