How to add memory management to a static TSubclassOf class variable in C++?

Hello! I have a certain use case where I have a static member variable of a UClass

UCLASS()
class USomeManager : public UWorldSubsystem
{
public:
    static TSubclassOf<SomeUClass> InitializerClass;
}

I would like to ensure that when assign a value to that variable, the instance won’t get garbage collected.

As far as I understand, I can’t UPROPERTY() a static variable, and I don’t need it exposed in Blueprint anyway. It is strictly C++.

I’m trying to avoid making some other class like a GameInstanceSubsystem with it just a UPROPERTY to simulate a static memory-managed variable.

What are my options?

You can call AddToRoot() on the uclass (or any uobject) to prevent garbage collection.

If you need to change the variable you’ll probably also want to RemoveFromRoot() the old value. In that case making the variable private and using static getter/setter would be more appropriate.

Note that this is not a managed variable. The GC isn’t aware of that variable, and if the object was to be destroyed (eg. Actor), the variable value wouldn’t be automatically nulled. But since it’s a class, it shouldn’t happen as long as it’s added to root.

1 Like

Thank you for telling me about the AddToRoot/RemoveFromRoot. I’ve made a proper static setter for the static variable considering the different possibilities and called the AddToRoot/RemoveFromRoot at the appropriate times. It worked perfectly for my problem.