Destructors in UE

Do classes in UE need destructors? When I add new code via Unreal Editor it never has a destructor.

If they’re not needed, why?

UE4 has garbage collection. That’s why in most of the cases your classes should be derived from UObject. If you’re using pointers and custom non-UObject classes you’ll have to deal with memory cleaning yourself.

What about UObjects in which I’m dealing with pointers, is there a special way or do I simple make a normal destructor?

As far as pointers are UObject types and created/spawned via NewUObject/SpawnActor everything will be handled automatically. AFAIK UObjects also work fine with “new”.
You’ll need destructors for classes which are not derived from UObject, assuming there’s actually something to destroy.

What if I choose to create stuff that are not UObjects inside of UObjects? Is such a scenario likely to happen?

Yes it could happen of course. But currently you’re trying to solve problems that didn’t happen yet. I mean, that’s all depends on how you will use this kind of class, but well, that’s out of my area of knowledge now, would like to see replies on this subjects now too :slight_smile:

Yeah, okay :slight_smile:

If you want to do manual cleanup of things inside your UObject class, you can implement BeginDestroy (this is called when the object is marked for GC, but has not been deleted yet).

12 Likes

That’s the answer I was looking for, thanks :slight_smile:

Not sure if this just hasn’t aged well but in 5.3, by the time this function is called, the object has alreayd been stripped for parts, including its reference to the world. I traced the destruction process and the earliest accessible interface is the event OnDestroyed, which is broadcasted earlier on so this would probably work better.