Questions about CDO in the documentation

Hi, I found that in the documentation there is a sentence saying “All C++ UObjects are initialized on engine startup, and the engine calls their default constructor.”. Does this mean that all C++ UObjects with a default constructor create their own CDOs when engine starts, and after this moment, all CDOs exist somewhere in the memory? If this is the case, what about I have a very large UObject, for example, an object with an array of size 1GB. The allocator will allocate 1GB memory for this particular CDO?

My second question is about the next sentence, “If there is no default constructor, your UObject will not compile.”. What is default constructor? The cppreference says a default constructor is a constructor which can be called with no arguments. If there’s no user-defined constructors, the compiler will generate an implicit default constructor. Why in this case the documentation emphasizes “If there is no default constructor”?

If that array is initialized in constructor then yes, your CDO and each instance of that object will populate 1GB of memory. If that object is meant to be a singleton and that array is crucial, consider using the CDO as a singleton. You can get the CDO in C++ via GetDefault<USomeObject>() for a const version or GetMutableDefault<USomeObject>() for non-const version. You can also pass/return the CDO to blueprints just like a normal object.
If you want to keep working with instances, but avoid populating CDO object, you can add a check as such :

if (!HasAnyFlags(RF_ClassDefaultObject))
{
    // do stuff
}

Alternatively, create your own initialization function and call it whenever you create a new object instance.

Regarding second question I’m not sure what they mean. My guess is that in C++ you normally have the possibility to delete constructors (eg: USomeObject() = delete;) and that sentence in UE docs just warns you not to do that.

2 Likes

OK, I made a simple test, define a plain UCLASS UObject with a class member TArray of type int8. This array is initialized in the class constructor respectively with size 0, 500000000 and 1000000000. The memory usage of Unreal Editor is shown in the following figure:

This means that the CDO of a C++ UObject does exist in the memory, and takes as much memory as it needs.

That perfectly answers my question! Thank you!