I’m just getting started with UE4, coming over from Unity. I have a simple piece of code in which I’m moving a pawn a little along the X axis on every Tick event:
void AFlowPawn::Tick(float DeltaSeconds)
auto newLocation = new FVector(GetActorLocation().X + 0.1f, GetActorLocation().Y, GetActorLocation().Z);
As per my understanding, memory is getting allocated to the heap when the new FVector executes. According the documentation, FVector doesn’t seem to inherit from UObject, so I’m a bit unclear if garbage collection is applicable.
Do I need to free this memory, or does Unreal Engine garbage collect this? If freeing is my responsibility, how do I do it?
You do not need dynamically allocated memory (the new operator) anywhere in that code.
When you use local variables, the memory is allocated automatically from the stack and cleaned up when the function returns.
void AFlownPath::Tick(float DeltaSeconds)
// local var, automatically managed:
FVector newPos = GetActorLocation();
newPos.X += 0.5f * DeltaSeconds;
Don’t use new/delete unless you really need it. I recommend some basic C++ tutorials for understanding memory management. It’s actually a lot easier than it looks, try not to over complicate things.
Ah of course. I instinctively used new because Unity vectors are structs, and you have to new them in C#. I’m not marking this as the answer because future readers might not be as naive as me, but this was the answer I needed.