Chapter 9. Templates and Commonly Used Containers

In Chapter 7, Dynamic Memory Allocation, we spoke about how you will use dynamic memory allocation if you want to create a new array whose size isn't known at compile time. Dynamic memory allocations are of the form int * array = new int[ number_of_elements ].

You also saw that dynamic allocations using the new[] keyword require you to call delete[] on the array later, otherwise you'd have a memory leak. Having to manage memory this way is hard work.

Is there a way to create an array of dynamic size and have the memory automatically managed for you by C++? The answer is yes. There are C++ object types (commonly called containers) that handle dynamic memory allocations and deallocations automatically. UE4 provides a couple of container types to store your data in dynamically resizable collections.

There are two different groups of template containers. There is the UE4 family of containers (beginning with T*) and the C++ Standard Template Library (STL) family of containers. There are some differences between the UE4 containers and the C++ STL containers, but the differences are not major. UE4 containers sets are written with game performance in mind. C++ STL containers also perform well, and their interfaces are a little more consistent (consistency in an API is something that you'd prefer). Which container set you use is up to you. However, it is recommended that you use the UE4 container set since it guarantees that you won't have cross-platform issues when you try to compile your code.

Debugging the output in UE4

All of the code in this chapter (as well as in the later chapters) will require you to work in a UE4 project. For the purpose of testing TArray, I created a basic code project called TArrays. In the ATArraysGameMode::ATArraysGameMode constructor, I am using the debug output feature to print text to the console.

Here's how the code will look:

ATArraysGameMode::ATArraysGameMode(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP)
{
  if( GEngine )
  {
    GEngine->AddOnScreenDebugMessage( 0, 30.f, FColor::Red,  "Hello!" );
  }
}

If you compile and run this project, you will see the debug text in the top-left corner of your game window when you start the game. You can use a debug output to see the internals of your program at any time. Just make sure that the GEngine object exists at the time of debugging the output. The output of the preceding code is shown in the following screenshot:

Debugging the output in UE4
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.251.57