What are the benefits of doing .Get for a WeakPtr in Tick, instead of caching a regular pointer?

I noticed some of my coworkers getting a reference of a TWeakPtr in Tick by doing something like this

TWeakObjectPtr<AActor> ActorWeak;

void Tick(){
    if(AActor* ActorPtr= ActorWeak.Get()){
        ///...
    }
}

instead of just caching it once and null checking in the Tick.

Is there a benefit to doing something like this?

Weak pointers break circular dependencies of shared pointers. The don’t take ownership of the object they point to and become null once they are invalidated or garbage collected.

if you use shared pointers in the place of weak pointers then their use count can be inflated causing them to not get gc’d when out of scope as they will still be seen as used in other places.

Weak pointers don’t increase this count and can make a cut off point for things that would normally be shared pointers.

Otherwise the referenced object could be stuck in limbo, not being destroyed because you referenced it in tick in another class where it interferes with it’s later destruction, as it’s still being seen as used (where this should not override it’s right to destroy and be collected).

1 Like

I see… I suppose memory management would be more convenient.
But also to my understanding, it might be slower than a regular pointer because you have indirectly load the pointer from the TWeakPtr. Do you suppose the differences in speed are negligible in cases of iterating it multiple times in Tick?

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.