|
|
|
|
Object creation
When a C++ object is created, two events
occur:
- Storage is allocated for
the object.
- The
constructor is called to initialize that
storage.
By now you should
believe that step two always happens. C++ enforces it because
uninitialized objects are a major source of program bugs. It doesn’t
matter where or how the object is created – the constructor is always
called.
Step one, however, can occur in several
ways, or at alternate
times:
- Storage can be allocated
before the program begins, in the static storage area. This storage exists for
the life of the
program.
- Storage can
be created on the stack whenever a particular execution point is reached (an
opening brace). That storage is released automatically at the complementary
execution point (the closing brace). These stack-allocation operations are built
into the instruction set of the processor and are very efficient. However, you
have to know exactly how many variables you need when you’re writing the
program so the compiler can generate the right
code.
- Storage can be
allocated from a pool of memory called the heap (also known as the free store).
This is called dynamic memory allocation. To allocate this memory, a function is
called at runtime; this means you can decide at any time that you want some
memory and how much you need. You are also responsible for determining when to
release the memory, which means the lifetime of that memory can be as long as
you choose – it isn’t determined by
scope.
Often these three
regions are placed in a single contiguous piece of physical memory: the static
area, the stack, and the heap (in an order determined by the compiler writer).
However, there are no rules. The stack may be in a special place, and the heap
may be implemented by making calls for chunks of memory from the operating
system. As a programmer, these things are normally shielded from you, so all you
need to think about is that the memory is there when you call for
it.
|
|
|