TWeakObjectPtr questions

I have a quick question regarding TWeakObjectPtr.

Is it good practice to use them for all actors spawned in the world? From what I understand, the world owns spawned actors so using a weakobjptr is fine as long as you check it is valid.

Even within programs, creating a strong pointer while casting or just getting actors is fine?

Good practice would be to use AActor* or TObjectPtr (or subclasses). Use them as-is for passing around in functions. For storing them in memory, wrap them with UPROPERTY in an UCLASS-decorated object instance, such as another actor or a world subsystem.

TWeakObjectPtr is kinda for advanced use, if you need to store an actor in memory outside of an UCLASS, for example in a static variable. It has more purpose with UObject types (not AActor) as you get to reference the object without preventing its garbage collection, while still benefitting from being able to check its validity post-destruction.

1 Like

I could see a reasonable argument to be made that any AActor* property could/should be a TWeakObjectPtr, however in practice it’s not really worth the effort.

First, weak pointers are meant to control garbage collection lifetimes (by being a reference that doesn’t prevent GC) however Actors don’t participate in normal GC. They have the reference from the work and will always be destroyed if that work goes away or they are directly destroyed. Having a weak or strong pointer to the Actor has no effect one way or another.

Second, even with a raw pointer (or TObjectPtr for properties) calling IsValid is generally sufficient to determine if the pointer that you have is no pointing to a valid actor.

Third, in some cases it can be easier to hook into the actor lifetime calls to manage those references. Like with a subsystem that does something with a certain Actor type, having that type add and remove itself from the subsystem in Begin/EndPlay provides a strong guarantee that you won’t have any bad references in your subsystem. Of course this doesn’t work in all cases, but it can be worth considering.

1 Like