Detect object reallocation

Sometimes you want to keep track of an object without declaring that you own its reference with NewRef(), thus allowing it to get deallocated even while you are keeping a reference to it. How to do it in a safe way and detect that it was deallocated/reallocated?

What to do when you start storing a reference

When you first get an instance of AcediaObject you'd like to store in such a way, check if it's allocated and remember its life version:

var int             storedReferenceLifeVersion;
var AcediaObject    storedReference;

function Store(AcediaObject newReference)
{
    if (newReference == none)           return;
    if (!newReference.IsAllocated())    return;

    storedReference             = newReference;
    storedReferenceLifeVersion  = newReference.GetLifeVersion();
    //  Not calling `newReference.NewRef()`, so `newReference` can get
    //  deallocated at any time!
}

What to do when you want to check if stored reference was deallocated

Before using such reference again you simply need to check if life version has changed. If it did, then this instance was reallocated and repurposed and you shouldn't use it anymore. Othewrwise it is still the same object.

function AcediaObject Get()
{
    if (storedReference == none) {
        return none;
    }
    if (storedReference.GetLifeVersion() != storedReferenceLifeVersion)
    {
        //  This object was reallocated! Time to forget about it.
        storedReference = none;
    }
    return storedReference;
}