我有一些代码,使用 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()
了...调用析构函数的方式,尽管这是允许的,但真的很丑陋,感觉就像一个黑客(确实如此)。