vrijdag 15 juni 2007

Automatic Static and Dynamic storage

C++ has three ways of managing memory for data, depending on the method used to allocate memory: automatic storage, static storage, and dynamic storage, sometimes called the free store or heap. Data objects allocated in these three ways differ from each other in how long they remain in existence.

Automatic Storage
Ordinary variables defined inside a function use automatic storage and are called automatic variables. These terms mean that variables come into existence automatically when the function containing them is invoked, and they expire when the function terminates.

Actually, automatic values are local to the block that contains them. A block is a section of code enclosed between braces. So far, all our blocks have been entire functions. But as you will see later, you can have blocks within a function. If you define a variable inside one of those blocks, it exists only while the program is executing statements inside the block.

Static Storage
Static storage is storage that exists throughout the execution of an entire program. There are two ways to make a variable static. One is to define it externally, outside a function. The other is to use the keyword static when declaring a variable:

static double fee = 56.50;

Later we will get deeper into this topic. For now, remember a automatic variable has a shorter lifetime then a static variable, the latter is existing during the execution of the whole program, the automatic comes into action when the block it is in is executed, and gets destroyed once the block ends.

Dynamic Storage
The new and delete operators provide a more flexible approach than automatic and static variables. They manage a pool of memory, which C++ refers to as the free store. This pool is separate from the memory used for static and automatic variables. new and delete enable you to allocate memory in one function and free it in another function. Thus the lifetime of the data is not tied arbitrarily to the life of the program or the life of a function.
Using new and delete together gives you much more control over how a program uses memory than does using ordinary variables.

Geen opmerkingen: