# 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**: `ObjectsContext` typically owns its children. - **Shared Access**: Use `SmartPointer` for objects shared across multiple systems (e.g., Geant4 and VTK). - **Core Principle**: Avoid manual `delete` on objects managed by the framework. ## Patterns ### 1. Context Ownership When an object is added to an `ObjectsContext`, it is managed by that context. ```cpp 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` for resources like `Material` or `Solid` that are used by both domain logic and external engines (Geant4). ```cpp uLib::SmartPointer 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_guard` if synchronizing transformations between `uLib::Object` and 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 `ObjectsContext` or `SmartPointer`. - **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 `SmartPointer` used for shared resources? - [ ] Is there a risk of double-freeing Geant4-managed pointers?