我有一些代碼使用malloc/realloc爲類分配內存,然後再次使用free刪除它們。下面是什麼我的工作的摘錄:使用malloc/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不會調用類的構造函數,但是這是由初始化函數處理。我的問題是:我如何處理釋放內存的方式,這種方式也會調用類的析構函數(類通常具有動態分配的內存,並且需要刪除它)?
謝謝!
在C中,你沒有類,而在C++中,你不應該使用'malloc' /'free'。你想寫什麼,你爲什麼這樣做? –
你沒有說你爲什麼不能使用new並自動刪除哪個構造函數/析構函數。這有什麼理由嗎? – Dabo
即使你有一個'原始字節數組'(例如'char *'),它可能會導致你(可能是'純C'程序員)使用'* alloc',你可以使用'new'和'delete' 。只是一個遠射,但你可以使用'std :: vector'來表示'offset'。 –