How to properly instantiate an UObject-derived class within a AActor-derived class ?


I have a custom class derived from UObject which deals with HTTP-transmission (I called it UHttpCommunication). It is supposed to be aggregated by other classes which need such communication.
Now I created a custom AActor-derived class which needs some HTTP communication, so I added a member which points to my UHttpCommunication-class and I instantiate it using NewObject<UHttpCommunication>() in the constructor. However I regularly get crashes, because the GC deletes my HttpCommunication instance while the actor is still alive.
I’ve also tried to declare the pointer to UHttpCommunication as UPROPERTY(Transient, DuplicateTransient), but it won’t really help.
I’m assuming I’m doing something wront with the aggregation.

Can somebody help ?

Hi’ya Lennert,

I had a similar situation, and solved it by adding the UWhatever instances to the root set after creation, i.e. YourUInstance->AddToRoot(). This protects the object from GC, so you don’t get the problem with stuff suddenly disappearing.

Two notes:

  1. I’m not claiming this solution is an example of “best practice” (maybe it is, maybe it isn’t) - only that it works.

  2. By explicitly evading GC, you assume the responsibility of managing the object’s lifetime yourself, so when the owning object is about to be destroyed, you should make sure to call YourUInstance->RemoveFromRoot() where relevant, so they can be cleaned up.

Addendum: Aside from that, I’ve got pretty much the same setup: i.e. creation via NewObject and all that. I don’t have any particular UPROPERTY decorations on the declaration (none, in fact).

this seems to have fixed the issue. thank you very much :slight_smile: