Storage allocation
A variable can now be defined at any
point in a scope, so it might seem that the storage for a variable may not be
defined until its point of definition. It’s actually more likely that the
compiler will follow the practice in C of allocating all the storage for a scope
at the opening brace of that scope. It doesn’t matter because, as a
programmer, you can’t access the storage (a.k.a. the object) until it has
been defined[41].
Although the storage is
allocated at the beginning of
the block, the constructor call doesn’t happen
until the sequence point where the object is defined because the identifier
isn’t available until then. The compiler even checks to make sure that you
don’t put the object definition (and thus the constructor call) where the
sequence point only
conditionally passes through it, such as in a
switch statement or
somewhere a goto can jump
past it. Uncommenting the statements in the following code will generate a
warning or an error:
//: C06:Nojump.cpp
// Can't jump past constructors
class X {
public:
X();
};
X::X() {}
void f(int i) {
if(i < 10) {
//! goto jump1; // Error: goto bypasses init
}
X x1; // Constructor called here
jump1:
switch(i) {
case 1 :
X x2; // Constructor called here
break;
//! case 2 : // Error: case bypasses init
X x3; // Constructor called here
break;
}
}
int main() {
f(9);
f(11);
}///:~
In the code above, both the goto
and the switch can potentially jump past the sequence point where a
constructor is called. That object will then be in scope even if the constructor
hasn’t been called, so the compiler gives an error message. This once
again guarantees that an object
cannot be created unless it is also initialized.
All the storage allocation discussed here
happens, of course, on the stack. The storage is
allocated by the compiler by moving the stack pointer “down” (a
relative term, which may indicate an increase or decrease of the actual stack
pointer value, depending on your machine). Objects can
also be allocated on the heap using new, which is something we’ll
explore further in Chapter
13.