Memory Model
Feature: Memory Model
Section titled “Feature: Memory Model”EntropyCore employs a hybrid memory model that combines intrusive reference counting with safe weak references and optional shared_ptr interoperability.
Core Concepts
Section titled “Core Concepts”EntropyObject
Section titled “EntropyObject”The base class for all managed objects. It provides:
- Intrusive Reference Counting: Thread-safe
refCountembedded in the object. - Weak Reference Support: Lazily allocated control block for weak pointers.
- Handle Identity: Optional ownership tracking for handle-based systems.
RefObject<T>
Section titled “RefObject<T>”The primary smart pointer for EntropyObject.
- Similar to
std::intrusive_ptrorboost::intrusive_ptr. - Zero allocation (pointer size only).
- Fast (direct atomics, no external control block for strong refs).
// Create a ref-counted objectRefObject<Texture> texture = makeRef<Texture>("hero.png");
// Pass by value (increments refcount) or const referencevoid render(RefObject<Texture> tex);WeakRef<T>
Section titled “WeakRef<T>”A non-owning reference that safely detects object destruction.
- Uses a
WeakControlBlockmanaged by the object. - Thread-safe
lock()returns aRefObject<T>.
WeakRef<Texture> weakTex = texture;
if (auto locked = weakTex.lock()) { // Object is alive and guaranteed to stay alive in this scope locked->bind();} else { // Object has been destroyed}std::shared_ptr Interoperability
Section titled “std::shared_ptr Interoperability”While RefObject is preferred for internal engine use, std::shared_ptr is supported for integration with external libraries or legacy code.
toSharedPtr
Section titled “toSharedPtr”Converts an EntropyObject to a std::shared_ptr that shares ownership with the intrusive refcount.
#include <EntropyCore/Core/EntropyInterop.h>
RefObject<MyObject> obj = makeRef<MyObject>();
// Create a shared_ptr that increments the INTRUSIVE refcountstd::shared_ptr<MyObject> shared = toSharedPtr(obj);Note: The custom key-holder ensures that std::shared_ptr calls release() instead of delete.
fromSharedPtr
Section titled “fromSharedPtr”Converts a compatible std::shared_ptr back to RefObject.
RefObject<MyObject> back = fromSharedPtr(shared);Best Practices
Section titled “Best Practices”- Use
RefObjectby default: control block is smaller (none), faster (intrusive). - Use
WeakReffor cycles: Parent -> Child (Strong), Child -> Parent (Weak). - Avoid
std::shared_ptrinside hot loops: Extra allocations/indirection unless needed for external APIs.