Hi! I’ve read through the docs many times, still this question remains ambigious to me. Right now, for every Uobject I have, I put UPROPERTY() on top of it. I do it because I think its the only proper way to make it garbage collected.
Now, maybe this is redundant? Somehow I notice, that if I forget to put UPROPERTY(), it does not seems that I am getting any kind of memory leaks during the level changes.
Is there some important think I am missing to all this?
If you create a UObject, UE4 counts the number of things that references it. Once that number of references hits zero, UE4 deletes it when it feels like it. If you need to store a pointer to the UObject in your class, because you’ll be referring to it later, then putting a UPROPERTY() over it tells Unreal Engine to keep a non-zero number of references to it. Therefore, when UE4 looks at the UObject, it will see that it’s still in use and keep it around.
The problem is not memory leaks… it’s UE4 deleting the object before you’re done with it.
Imagine you have a texture or a particle system. If you don’t keep the pointer in a UPROPERTY(), UE4 will think you don’t need it anymore and garbage collect it. Then, if you try to use it, it’s not there. The pointer is null. You will even crash if you forget to do a null pointer check when you try to use it.
Ah! It all makes sense now, thank you! Its not GC I should be worry about, but rather think do I need those pointer to be available all the time to me, or not.
Basically, yeah. If you’re storing a pointer, then that implies you want to access the pointed thing at some time in the future. That’s not sufficient for UE4, because it needed a little more data than it could get from standard C++ syntax. All of that metadata is hidden in the UPROPERTY() macro.
C++ would normally just leave it there forever until you explicitly ask for it to be gone (which leads to memory leaks). UE4 will delete it when it feels like it, unless you explicitly say “I’ma need this for a while”.
Note that it’s not just “do I need that pointer to be available to me.”
If you don’t decorate the pointer to UObject with UPROPERTY(), and the object gets collected (destroyed,) you are now left with an invalid pointer that will likely crash the next time you use it. It will NOT be auto-set to NULL when the pointed-to object gets deleted.