Download

TSharedPtr vs UObjects

Does anybody know why we cannot use TShared pointers and references (which are awesome features) with UObjects ? :confused:
And if possible, explain why is life supposed to be like that…

If make something like this:

UPROPERTY()
UObject* pointerToObject;

It is already behaving like shared pointer.

You can’t use references for anything declared in header, as references must be initialized upon declaration. You can pass UObjects as references in functions, or return them as references for locally declared variables (not sure about this last one and can’t check it right now).

Why ypu can’t use TSharedPtr and TSharedRef with UObject I can’t say right now, without looking at code (which I can’t do right now).

Instead you can use TWeakObjectPtr<> for weak pointers of UObjects

As far as I understand it, in case of UObjects ownership is always with the engine. Which is why you can have weak refs.
Everything pointed to by a TSharedPtr is basically behaving like a “regular” shared pointer so the ownership lies with you.

HTH,
Moose