- Unreal Engine 4.x Scripting with C++ Cookbook
- John P. Doran William Sherif Stephen Whittle
- 162字
- 2025-02-28 12:28:31
Managed memory – using NewObject< > and ConstructObject< >
Managed memory refers to memory that is <indexentry content="managed memory:allocating, NewObject used">allocated and de-allocated by some programmed subsystem above the new, delete, malloc,, and free calls in C++. These subsystems are commonly created so that the programmer does not forget to release memory after allocating it. Unreleased, occupied, but unused memory chunks are called memory leaks, as follows:
// generates memory leaks galore!
for( int i = 0; i < 100; i++ )
{
int** leak = new int[500];
}
In the preceding example, the memory allocated is not referenceable by any variable! So, you can neither use the allocated memory after the for loop, nor free it. If your program allocates all available system memory, then what will happen is that your system will run out of memory entirely, and your OS will flag your program and close it for using up too much memory.
Memory management prevents forgetting to release memory. In memory-managed programs, it is commonly remembered by objects that are dynamically <indexentry content="managed memory:allocating, ConstructObject used">allocated the number of pointers referencing the object. When there are zero pointers referencing the object, it is either automatically deleted immediately, or flagged for deletion on the next run of the garbage collector.
Use of managed memory is automatic within UE4. Any allocation of an object to be
used within the engine must be done using the NewObject< >() or SpawnActor< >() function.
The release of objects is done by removing the reference to the object and then occasionally calling the garbage cleanup routine (listed further in this chapter).