Game Development Reference
In-Depth Information
Working with Heap Memory
So far in this topic I have avoided using dynamic memory as much as possible because manually
managing dynamically allocated memory is sometimes challenging, slower than using stack memory,
and also very often unnecessary. Managing dynamic memory will become more important for you
once you advance to writing games that load data from external files, as it's often impossible to
tell how much memory you'll need at compile time. The very first game I worked on prevented
programmers from allocating dynamic memory altogether. We worked around this by allocating
arrays of objects and reusing memory in these arrays when we ran out. This is one way to avoid the
performance cost of allocating memory.
Allocating memory is an expensive operation because it has to be done in a manner that prevents
memory corruption where possible. This is especially true on modern multiprocessor CPU
architectures where multiple CPUs could be trying to allocate the same memory at the same time.
This chapter, like the last, is not intended to be an exhaustive resource on the topic of memory
allocation techniques for game development, but instead introduces the concept of managing
heap memory.
You saw the use of the new and delete operators in Chapter 21 when creating the Singleton
EventManager object. Listing 22-2 shows a simple program using the new and delete operators.
Listing 22-2. Allocating Memory for a class Dynamically
class Simple
{
private:
int variable{ 0 };
public:
Simple()
{
std::cout << "Constructed" << std::endl;
}
~Simple()
{
std::cout << "Destroyed" << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Simple* pSimple = new Simple();
delete pSimple;
pSimple = nullptr;
return 0;
}
 
Search WWH ::




Custom Search