What About Arrays?
So far today, we've only been looking at individual values. But we should also make sure we can reason about object lifetimes for arrays of values.
That seems exponentially more complicated.
It's not so bad!
Arrays are exactly the same as individual values; each phase of life just happens N times for an array of N values!
Allocation Phase
Allocation happens at the same time as for individual objects, but space for all N values is allocated at once.
So
Hedgehog array[5]
(see here) will allocate space for fiveHedgehog
s on the stack?Exactly!
Initialization Phase
Initialization follows the same timing rules as individual objects, but will happen N times: once for each element of the array (in order).
For a default-initialized array of N instances of a class, the default constructor will be called N times!
Use Phase
Use happens in the same way as for individual objects, for each individual element of the array.
Destruction Phase
Destruction follows the same timing rules as individual objects, but will happen N times: once for each element of the array.
For an array of N instances of a class, the destructor will be called N times!
Mirroring the “destruction is the inverse of construction” idea, elements are destroyed in reverse order (i.e., last element destroyed first; first element destroyed last).
Deallocation Phase
I think I'm seeing a pattern here. Let me guess:
Deallocation follows the same timing rules as individual objects, but space for all N _values is deallocated at once.Yup!
Practice Problem
Suppose we have the following member functions in our Cow
class,
Cow::Cow() {
cout << "Cow default constructor called" << endl;
}
Cow::~Cow() {
cout << "Cow destructor called" << endl;
}
…and the following program that uses our Cow
class,
int main() {
Cow herd[5];
Cow bessie;
Cow mabel{3, 13};
}
(When logged in, completion status appears here.)