What are the TPtr Templates? When to use each one?

I see some template to hold references to variables:

TSubobjectPtr<class Foo> variable;
TSubclassOf<class Foo> variable;

I can also do plain pointer references:

class Foo* variable;

What are all the pointer-like templates for referencing stuff?

When should I use each option?

TSubobjectPtr is a special wrapper designed to be used for components of actors. It means “This object is of type foo, and is a subobject”. It’s main use to prevent other coders from modifying the pointer after the object has been created, because certain types of modifications are unsafe to perform on subobjects. When used, it is only important to use within the header file of the actor, and otherwise it should be used as a normal Foo*.

TSubclassOf is a wrapper that is used when you want to refer to UClass objects. It means “This object is a UClass, and that UClass inherits from foo”. This is very useful when you want to refer to a data defined blueprint, that inherits from native class Foo. You can then be certain that only subclasses of Foo are valid to be saved into that pointer, and if you use it as a UProperty, the class selector in the editor will correctly filter to only show valid subclasses of Foo.

TWeakObjectPtr is another useful one, this allows you safely refer to a UObject, but without holding a hard reference that will stop the object from being garbage collected. It means “This is a weak reference to an object, of type Foo”. It’s very useful for things like UI, where you want to know about the state of an object, but are able to continue if it gets garbage collected

@Ben - Is there ever an appropriate time to use the built in * pointer or should one always look to use these provided template pointers?

Great, thanks!

You want to use a UPROPERTY raw * when you want a Hard reference, which is one that stops the referenced object from being deleted. By making it a UPROPERTY the Garbage collection system will know about it and keep the reference alive.

You basically never want to have a raw * to a UObject that isn’t a UPROPERTY, because the GC system won’t know about it, and that raw * may end up getting corrupted

Sorry to dredge up an old thread but I’m a bit confused. I made a first person C++ project and in the HUD header file it autocreates I noticed a “class UTexture2D* CrosshairTex” declaration. What would be the reason this is declared as just a raw pointer given that it’s not a UPROPERTY (which if I’m interpreting your response right, is something that you basically never want to have)? Furthermore, how does it get cleaned up? I don’t notice any manual deletes in the templated project, and it’s not using one of the TPtr templates. Thanks!