Will this code be garbage collected?

so in the header I declare:

//Hit result from raycast to cover volume
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = MainCharacterCoverData)
        FHitResult HitHead;

And then in the code I am doing this:

HitBottom = *( new FHitResult(ForceInit) );
HitHead = *( new FHitResult(ForceInit) );

I was looking for a way to destroy what was stored in the variables before I stored something else in them, but then I came across something talking about how Uproperties are garbage collected. Very very rusty at C++ and new to UE4 coding, so any help would be greatly appreciated.

HitBottom = *( new FHitResult(ForceInit) );

Why are you writing this way?

What you’ve done here is create a UPROPERTY for a struct. There’s no reason for that to be garbage collected because it’s not dynamic memory.

When you use the new operator you do allocate memory. However, in this case you immediately dereference the newly created pointer and copy the data into your existing struct. That new pointer is not a UPROPERTY. The way you’ve written it, that pointer can’t be deallocated because nothing references it after it’s created.

Unless UE4 does some magic I’m not aware of, it can’t garbage collect that pointer.

What you doing is actually pure memory leak, you dynamicly creating structure then copy it to staticly declered struct (non-pointer) and and right away throw away what you allocated. Statically declared objects and structs varables don’t need initiation, they are ready to go right away when you declere them, so you don’t need use “new” as all, just set varables in struct that you want or call constructor without “new” FHitResult(ForceInit), same as you do with FVector(X,Y,Z), compiler simply gonna execute constructor on static varable

I can’t tell much about uproperty, as 100% of my C++ experience is outside of UE4, but one thing is sure, if you see a memory leak potential, don’t allow it. even if garbage collector (which is hurting C++ ideology deeply) will collect it, you would get more performance when avoiding that.

my own advice: if you manage to turn off garbage collector, just - do -it.
C++ is all about shooting yourself in the leg - that’s all the fun, not garbage collected kittens and rainbows.