Garbage Collection ~ Count References To Any Object

From Epic Wiki
Jump to: navigation, search

Overview

Original Author: Rama (talk)

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<UObject*>* OutReferredToObjects = nullptr)
{
	if(!Obj || !Obj->IsValidLowLevelFast()) 
	{
		return -1;
	}
	
	TArray<UObject*> 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 an array to my function if you want to know exactly who the object is referring to!

TArray<UObject*> ReferredToObjs;

GetObjReferenceCount(this,&ReferredToObjs);

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

ObjRefCount.jpg

Conclusion

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

Enjoy!

Rama (talk)