11.1 Memory Allocation


11.1 Memory Allocation

There are often times when it is useful to control the creation of objects in memory. By this, I mean an object of a specified data type and controlling when it is created and when it is destroyed. For example, say I want to keep a list of 10 random numbers. This list might be generated in one function and used in another. I can keep a reference to the list through a global pointer, but what happens when I have no further use for the list? Previously we determined a variable's lifespan exclusively by its scope, and we relied on them being created and destroyed as the variables entered and left scope, such as global, local, and block. We defined global variables to have global scope throughout an application, accessible anywhere; local variables to exist only within the scope of functions or classes; and block variables to exist only within blocks of code such as loops and conditional statements, or anywhere within braces ({}).

What we want to do now is create variables on demand and also destroy them on demand, so the memory they occupied is freed and can be used by something else, such as newly created variables. The process of manually creating variables in memory and manually controlling their deletion is called dynamic memory allocation because it happens during run time (on the fly).




Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net