How to free a locally allocated FVector?

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);
	SetActorLocation(*newLocation, true);

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?


Yes, you should it delete.

delete newLocation;

Best Regards,

Thanks, .

Out of curiosity, what if in the Tick() it was set as

SetActorLocation(FVector(GetActorLocation.X + 0.1f, GetActorLocation.Y, GetActorLocation.Z));


FVector newPos = FVector(GetActorLocation.X + 0.1f, GetActorLocation.Y, GetActorLocation.Z);

Would we need to do our own memory management anywhere here?

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.

Simply use:

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. :slight_smile:

Hello Dune,

No, in this example you create variables locally (in stack). You should free memory only when allocate memory in heap (new, malloc, etc).


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.