// This code implementation is the intellectual property of // the GEANT4 collaboration. // // By copying, distributing or modifying the Program (or any work // based on the Program) you indicate your acceptance of this statement, // and all its terms. // // $Id: G4Allocator.hh,v 1.6 2001/01/09 07:50:57 stesting Exp $ // GEANT4 tag $Name: geant4-03-01 $ // // // ------------------------------------------------------------ // GEANT 4 class header file // // History: first implementation, based on object model of // 2nd December 1995, G.Cosmo // ---------------- G4Allocator ---------------- // by Tim Bell, September 1995 // ------------------------------------------------------------ // SG, HPW: Protection vs double deletion of the same element, June 97. #ifndef G4Allocator_h #define G4Allocator_h 1 #include #include // G4AllocatorPage #include "G4AllocatorPage.hh" template class G4Allocator { G4AllocatorPage *fPages; G4AllocatorUnit *fFreeList; private: void AddNewPage(); Type *AddNewElement(); enum { Allocated = 0x47416C, Deleted = 0xB8BE93 }; public: G4Allocator(); ~G4Allocator(); inline Type *MallocSingle() { Type *anElement; if (fFreeList != NULL) { fFreeList->deleted = Allocated; anElement = &fFreeList->fElement; fFreeList = fFreeList->fNext; } else anElement = AddNewElement(); return anElement; } inline void FreeSingle(Type *anElement) { G4AllocatorUnit *fUnit; fUnit = (G4AllocatorUnit *) ((char *) anElement - offsetof(G4AllocatorUnit, fElement)); if (fUnit->deleted == Allocated) { fUnit->deleted = Deleted; fUnit->fNext = fFreeList; fFreeList = fUnit; } /* else if (fUnit->deleted == Deleted) { // G4cerr << "G4Allocator : This object is already deleted" << G4endl; } else { // G4cerr << "G4Allocator: This object is allocated not by G4Allocator"<< G4endl; } */ } }; template G4Allocator::G4Allocator() { fPages = NULL; fFreeList = NULL; AddNewPage(); return; } template G4Allocator::~G4Allocator() { G4AllocatorPage *aPage; G4AllocatorPage *aNextPage; aPage = fPages; while (aPage != NULL) { aNextPage = aPage->fNext; free(aPage->fUnits); delete aPage; aPage = aNextPage; } fPages = NULL; fFreeList = NULL; return; } static const G4int G4AllocatorPageSize = 1024; template void G4Allocator::AddNewPage() { G4AllocatorPage *aPage; register G4int unit_no; aPage = new G4AllocatorPage; aPage->fNext = fPages; aPage->fUnits = (G4AllocatorUnit *) malloc(G4AllocatorPageSize); fPages = aPage; for (unit_no = 0; unit_no < (G4AllocatorPageSize / G4int(sizeof(G4AllocatorUnit))-1); ++unit_no) { aPage->fUnits[unit_no].fNext = &aPage->fUnits[unit_no + 1]; } aPage->fUnits[unit_no].fNext = fFreeList; fFreeList = &aPage->fUnits[0]; } template Type *G4Allocator::AddNewElement() { Type *anElement; AddNewPage(); fFreeList->deleted = Allocated; anElement = &fFreeList->fElement; fFreeList=fFreeList->fNext; return anElement; } #endif