在类中使用malloc/free
Using malloc/free with classes
我有一些代码,使用 malloc/realloc 为类分配内存,然后使用 free 再次删除它们。以下是我正在使用的内容的摘录:
void NewSubInstances()
// Invoked by each worker thread to grow the subinstance array and
// initialize each new subinstance using a particular method defined
// by the subclass.
{
if (slavetotalspace >= totalobj) { return; }
//Remember current large size
G4int originaltotalspace = slavetotalspace;
//Increase its size by some value (purely arbitrary)
slavetotalspace = totalobj + 512;
//Now re-allocate new space
offset = (T *) realloc(offset, slavetotalspace * sizeof(T));
if (offset == 0)
{
G4Exception("G4VUPLSplitter::NewSubInstances()",
"OutOfMemory", FatalException, "Cannot malloc space!");
return;
}
//The newly created objects need to be initialized
for (G4int i = originaltotalspace; i < slavetotalspace; i++)
{
offset[i].initialize();
}
}
void FreeSlave()
// Invoked by all threads to free the subinstance array.
{
if (!offset) { return; }
free( offset);
offset = 0;
}
我知道 malloc 不会调用类的构造函数,但这是由初始化函数处理的。我的问题是:我如何以调用类析构函数的方式处理内存的释放(类通常具有动态分配的内存,需要删除它)?
谢谢!
我怎样才能以一种调用类析构函数的方式处理内存的释放(类通常具有动态分配的内存,需要删除它)?
您的问题的答案如下所示:
void FreeSlave()
{
if (!offset)
{ return; }
// call destructors explicitly
for(G4int index = 0; index < slavetotalspace; ++index)
offset[index].~T();
free( offset);
offset = 0;
}
也就是说,不要在C++中使用malloc/realloc/free(不,即使这里有任何借口)。虽然它可能会起作用(不确定),但这段代码晦涩难懂/具有不明显的依赖关系,很脆弱,难以理解,并且违反了最小意外原则。
另外,请不要将指针称为"偏移量",也不要在C++中使用 C 样式转换(这是不好的做法)。
您可以使用
:
void FreeSlave()
{
if (!offset) { return; }
for (G4int i = slavetotalspace; i != 0; --i) {
offset[i - 1].~T();
}
free(offset);
offset = 0;
}
我建议有一个destroy()
的方法......既然你已经initialize()
了...调用析构函数的方式,尽管这是允许的,但真的很丑陋,感觉就像一个黑客(确实如此)。
相关文章:
- 在 malloc 之后检查 &在调用 free() 之前
- Malloc()/free()在Windows上的几个线程中崩溃
- 如果在 C++ 中的 malloc() 之后调用 free() 则会出现错误
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 如果malloc/free对显然做了同样的工作,为什么C++标准库容器使用内存池
- 在类中使用malloc/free
- 在 C++ 中将 malloc/free 替换为 new/delete
- 如何将'malloc'和'free'替换为'new'和"删除"?
- 在C++中,"new/delete"在结构上代替"malloc/free"有多好?
- 基于malloc/free的STL分配器
- 使用 malloc/free 来模拟新建/删除
- 标准C++的哪些部分将调用malloc/free而不是new/delete
- C++中的 malloc/free 和 new/delete 兼容性
- 编译器将 malloc/free 或 new/delete 对优化为 alloca
- 为什么使用 malloc/free,当我们有 new/delete 时
- 嵌入式RTOS和使用malloc/free
- 将static_cast<字符 *>malloc/free/free转换为新的/删除
- c++中的malloc/free:为什么free不接受const void*,有没有更好的方法?
- 列出Xcode, iOS中最后的X malloc/free调用
- 用静态链接重新定义malloc/free有多个定义错误