1.7 KiB
1.7 KiB
Skill: Memory Management & Object Lifecycle
This skill provides guidelines for managing memory safely within the uLib framework to prevent memory corruption and leaks.
Context
- Ownership:
ObjectsContexttypically owns its children. - Shared Access: Use
SmartPointer<T>for objects shared across multiple systems (e.g., Geant4 and VTK). - Core Principle: Avoid manual
deleteon objects managed by the framework.
Patterns
1. Context Ownership
When an object is added to an ObjectsContext, it is managed by that context.
auto* context = new ObjectsContext();
auto* obj = new MyObject();
context->AddObject(obj);
// Do NOT delete obj; it will be deleted when context is destroyed.
2. Smart Pointers
Use SmartPointer<T> for resources like Material or Solid that are used by both domain logic and external engines (Geant4).
uLib::SmartPointer<Material> mat = new Material("Lead");
solid->SetMaterial(mat); // Shared ownership
3. Geant4 Object Safety
Geant4 often takes ownership of certain objects (like G4VPhysicalVolume). When wrapping these:
- Ensure the wrapper doesn't double-free the Geant4-owned pointer.
- Use
recursion_guardif synchronizing transformations betweenuLib::Objectand Geant4 volumes to prevent signal loops.
Debugging Memory Issues
- SIGABRT (invalid pointer): Usually caused by deleting an object that was already managed (and deleted) by an
ObjectsContextorSmartPointer. - Leaks: Check if objects were created but never added to a context or wrapped in a
SmartPointer.
Checklist
- Are objects added to an
ObjectsContext? - Is
SmartPointerused for shared resources? - Is there a risk of double-freeing Geant4-managed pointers?