Objects on the Stack
What do we know about when object lifetime events happen for things on the stack?
- Allocation happens at the opening curly brace of the function
- Initialization happens on the declaring line
- Destruction happens at the closing curly brace of the declaring block
- And deallocation happens at the closing curly brace of the function
Yup! That about does it! If you need a refresher, check out Week 1, Lesson 2
Summary of Object Lifetime Timing for Variables on the Stack
Phase | When does it happen? |
---|---|
Allocation | Opening { of function |
Initialization | Declaration line |
Use | …From initialization to destruction… |
Destruction | Closing } of declaring block |
Deallocation | Closing } of function |
Crucially, note that no matter what type of value an object is (primitive type or instance of a class), it will be allocated and initialized exactly once. In a well-formed program (no memory errors), values should also be destroyed and deallocated exactly once.
For values on the stack, the compiler makes sure we get that single destruction and deallocation by connecting them to function calls/returns.
Practice Exercise
Consider the following code, where the line numbers are there to help you refer to specific parts of the code, but are not part of the code:
1| int main() {
2| Cow bessie{"bessie"};
3| int x = 5;
4| }
(When logged in, completion status appears here.)