How UObject Grabe Collection works?

For example, I created an UObject derived class and I create a pointer in the class like that: SomeClass* foo = something. That object is getting automatically garbage collected?

Unless you’re using the foo pointer and/or there is something to reference it, the instance won’t be garbage collected.

Unreal implements a garbage collection scheme whereby UObjects that are no longer referenced or have been explicitly flagged for destruction will be cleaned up at regular intervals. The engine builds a reference graph to determine which UObjects are still in use and which ones are orphaned.

Unreal Object Handling in Unreal Engine | Unreal Engine 5.3 Documentation.

Next important sentence:

One practical implication here is that you typically need to maintain a UPROPERTY reference to any Object you wish to keep alive, or store a pointer to it in a TArray or other Unreal Engine container class.