Question about Garbage Collection
I have read the following guides on Unreal Garbage Collection:
I am left with the impression that every class field (member) should be marked with UPROPERTY() However there is one case that is bothering me and I am not sure about. Imagine we have this:
And the implementation of NativeInitialzeAnimation() is like so:
Now the question is, since we don't initialize the Owner in this fashion, for example:
this->Owner = NewObject();
Do we have to mark the raw pointer Owner with UPROPERTY()? My guess is no, because of the RAII principle. In other words the raw pointer is pointing to something that is already managed elsewhere. Is this correct?
asked Mar 19 '17 at 07:13 PM in C++ Programming
UPROPERTY is for properties you want to serialize, expose in the Editor, and have Unreal handle all the dynamic allocation, reference resolves, and such for. It's completely fine to have a naked pointer that you are assigning at run-time. A pointer is just an 32/64bit integer (depending on your platform) that contains a memory address, so it doesn't inherently need garbage collection.
Since you are just storing an address to an object that is already instantiated elsewhere, you're fine.
answered Mar 19 '17 at 07:54 PM
I guess it will be better to use TWeakObjectPtr Owner instead. You can use naked pointers safely only when your class is dependant from something it points to by its lifetime. Like some class and it's parent. The trouble you can get with raw pointer points to the Pawn owner is when pawn disconnects GC will remove actual pawn object and you'll get a broken pointer. TWeakObjectPtr will became null automatically at this situation. But you can use raw pointers to the hierarchical parent of component for example (because when parent object will be GC-ed all children will be removed too).
answered Mar 19 '17 at 11:35 PM
Follow this question
Once you sign in you will be able to subscribe for any updates here