Game Development Reference
In-Depth Information
This simple program shows new and delete in action. When you decide to allocate memory in C++
using the new operator, the amount of memory required is calculated automatically. The new operator
in Listing 22-2 will reserve enough memory to store the Simple object along with its member
variables. If you were to add more members to Simple or inherit it from another class, the program
would still operate and enough memory would be reserved for the expanded class definition.
The new operator returns a pointer to the memory that you have requested to allocate. Once you
have a pointer to memory that has been dynamically allocated, you are responsible for ensuring that
the memory is also freed appropriately. You can see that this is done by passing the pointer to the
delete operator. The delete operator is responsible for telling the operating system that the memory
we reserved is no longer in use and can be used for other purposes. A last piece of housekeeping
is then carried out when the pointer is set to store nullptr . By doing this we help prevent our code
from assuming the pointer is still valid and that we can read and write from the memory as though
it is still a Simple object. If your programs are crashing in seemingly random and inexplicable ways,
accessing freed memory from pointers that have not been cleared is a common suspect.
The standard new and delete operators are used when allocating single objects; however, there
are also specific new and delete operators that should be used when allocating and freeing arrays.
These are shown in Listing 22-3.
Listing 22-3. Array new and delete
int* pIntArray = new int[16];
delete[] pIntArray;
This call to new will allocate 64 bytes of memory to store 16 int variables and return a pointer to the
address of the first element. Any memory you allocate using the new[] operator should be deleted
using the delete[] operator, because using the standard delete can result in not all of the memory
you requested being freed.
Note Not freeing memory and not freeing memory properly is known as a memory leak. Leaking memory
in this fashion is bad, as your program will eventually run out of free memory and crash because it eventually
won't have any available to fulfill new allocations.
Hopefully you can see from this code why it's beneficial to use the available STL classes to avoid
managing memory yourself. If you do find yourself in a position of having to manually allocate
memory, the STL also provides the unique_ptr and shared_ptr templates to help delete the memory
when appropriate. Listing 22-4 updates the code from Listing 22-2 and Listing 22-3 to use unique_ptr
and shared_ptr objects.
 
 
Search WWH ::




Custom Search