Garbage Collection ~ Count References To Any Object

Overview Original Author: () For a more thorough background in this topic of Memory Management I recommend you check out my main Garbage Collection wiki first: Garbage Collection and Dynamic Memory...

Updated about 2 years ago Edit Page Revisions

Overview

Original Author: Rama

For a more thorough background in this topic of Memory Management I recommend you check out my main Garbage Collection wiki first:

Garbage Collection and Dynamic Memory Allocation

In this wiki I am providing you with an extremely handy memory management tool, which is the ability to count references to any UObject yourself!

Additionally you can supply an array if you want to know exactly who is referred to by your object!

Victory!

Code

static int32 URamaStaticFunctionLib::GetObjReferenceCount(UObject* Obj, TArray* OutReferredToObjects = nullptr)
{
    if(!Obj || !Obj->IsValidLowLevelFast())
    {
        return -1;
    }
    
    TArray ReferredToObjects;             //req outer, ignore archetype, recursive, ignore transient
    FReferenceFinder ObjectReferenceCollector(ReferredToObjects, Obj, false, true, true, false);
    ObjectReferenceCollector.FindReferences(Obj);

    if(OutReferredToObjects)
    {
        OutReferredToObjects->Append(ReferredToObjects);
    }
    return OutReferredToObjects.Num();
}

Who Is Referred to By My Object?

You can supply pass an array to my function if you want to know exactly who the object is referring to!

TArray ReferredToObjs;

GetObjReferenceCount(this,&ReferredToObjs);

for(UObject* Each : ReferredToObjs)
{
    if(Each)
    {
        UE_LOG(YourLog,Warning,TEXT("%s"), *Each->GetName());
    }
}

Image:ObjRefCount.jpg

Conclusion

This is all the info you need to do your own careful UPROPERTY() memory management!

Enjoy!

Rama