A general question about best practices and garbage collection.
When working with C++ with Rider and adding to a class an object pointer it will give the next warning:
Object member 'CapsuleComp' can be destroyed during garbage collection, resulting in a stale pointer
So to fix that I have two options:
- Add a
UPROPERTY
macro, expose it to Blueprints and to the UE Garbage Collection. - Wrap the type with an
TObjectPtr<T>
which also marks it for UE’s Garbage Collection (as the documentation states “When resolved, its participation in garbage collection is identical to a raw pointer to a UObject”.
But what I’ve noticed is that the UE API uses both, UPROPERTY marco and TObjectPtr, for example the UShapeComponent
class has:
UPROPERTY(transient, duplicatetransient)
TObjectPtr<class UBodySetup> ShapeBodySetup;
I’m wondering what is the best practice here?
When should I just use UPROPERTY
macro and when should I use both? Or only TObjectPtr<T>
?