Download

Using "new" and Heap Memory Management

Hello Everyone,

I’m looking to better understand the “new” expression and how Unreal Manages its memory.

  • Is the “new” expression congruent with the C++ version?
  • Do I need to be erasing instances I’ve instanced using new?
  • Do I need to worry about memory leaks in general? If so, how should I erase the potentially leaked memory?
  • Are there any good resources about UE4s Heap Handling to which I could be pointed?

Lastly, I was curious about using new in a function call. Would that be a memory leak? I made an example below. Is this an acceptable use of the “new” expression:

Func Def:
void DoFoo(FSomeStruct * InSomeStruct)
{
SomeStruct = InSomeStruct;
}

Code:
DoFoo(new FSomeStruct());

…More Code…

DoFoo(new FSomeStruct());

Thanks for your help everyone:)

With UE, you generally don’t use the new operator because all UObjects are automatically garbage-collected. Use NewObject, ConstructObject, and ConditionalBeginDestroy to create and destroy UObjects.

It’s okay to use new for FStructs are not pointers and they are not part of the garbage collection system. For UObject classes, use the appropriate factory method to get one. ie. NewObject() or SpawnActor()

Bear in mind that FStructs which aren’t in UObjects won’t be reachable by the garbage collector, so UPROPERTY UObject references in them won’t count for reachability: if the only reference to a UObject you created is in a struct on the heap, the GC will come along at some point and delete your UObject.

Unless you derive the struct from FGCObject | Unreal Engine Documentation and add the UObject to the FReferenceCollector in the AddReferencedObjects function.

1 Like