As I understand it, if you create a UObject on the heap using NewObject, it is [registered with UE4’s Garbage Collection system][1], so when all pointers are out of scope, it will be deleted from the heap automatically unless it is registered as a UPROPERTY. My question is, how does this relate to a UObject heap pointer that I return to a blueprint?
I’m looking to create a static library function that creates a UObject subobject on the heap and returns the pointer to a blueprint node. (There’s various applications for this pattern, for example I’d like to use it to return a custom path object to BP after some pathfinding C++ is run. It needs to return a new path object every time it’s called, so it can’t just return a pointer to some member UPROPERTY.)
Example code:
TestObject.h
//...
UCLASS()
class PATHFINDINGTEST_API UTestObject : public UObject
{
GENERATED_BODY()
// Insert UPROPERTYs and UFUNCTIONs etc. here...
};
PathfindingCodeLibrary.h
//...
UCLASS()
class PATHFINDINGTEST_API UPathfindingCodeLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintPure, meta = (FriendlyName = "Get me a test object pls"))
static UTestObject* GetTestObject(/* arguments... */);
};
PathfindingCodeLibrary.cpp
//...
UTestObject* UPathfindingCodeLibrary::GetTestObject(/* arguments... */)
{
// Registered for Garbage Collection
UTestObject* returnvalue = NewObject<UTestObject>();
// Populate returnvalue here...
return returnvalue;
}
And when all compiled, the function can be called from a blueprint:
So my question really is: what is the lifetime of the object in the above picture? Can I safely use the result from this BP node, or could the garbage collection attempt to delete it while it’s still in scope within BP, since it’s not registered as a UPROPERTY and there are no code references to it?
Also, assuming it is safe to use, will it be garbage collected safely once the node result is out of scope, or will it remain on the heap?
Thanks!