Key Points
- Object lifetime on the stack: when?
- Allocation: at the opening
{of the function - Initialization: at the declaring line
- Use: between initialization and destruction
- Destruction: at the closing
}of the declaring block - Deallocation: at the closing
}of the function
- Allocation: at the opening
- Default initialization/construction
int x;Cow mabel;Cow bessie{};- For an object, invokes the default (parameterless) constructor
- Copy initialization/construction
- Creates a new object that is a copy of an exiting object
int x = y;int a{b};Cow mabel = adeline;Cow bessie{fennel};- For an object, invokes the default constructor (which takes a reference to an object of the same type)
- Also used to initialize function parameters and return values
- Assignment operator
- Changes an existing object to be a duplicate of another existing object
s = t;cadewyn = ethyl;- For an object, invokes the assignment operator, a special member function called
operator=.
- Destructor
- A special member function that is automatically invoked when an object is destroyed
- For class
Cow, the destructor is named~Cow - Typically used to “clean up” or release any resources the object is holding onto
- The compiler can synthesize or disable these functions:
Cow(); // Means that the programmer will define the default constructorCow() = default; // Means that we will use the compiler's synthesized default constructorCow() = delete; // Means that this class does not have a default constructor- Same for default constructor, copy constructor, assignment operator, and destructor (but don't disable the destructor!!)
- For arrays, the same as above, only \( N \) times, where \( N \) is the size of the array.
- For references, initialization and destruction mark the usage period of the name
- We don't model any allocation or deallocation for references
- For data members of a class
- Allocation happens when the object is allocated
- Initialization happens before the opening
{of the constructor (so use the member-initialization list!) - Destruction happens at the closing
}of the destructor - Deallocation happens when the object is deallocated
(When logged in, completion status appears here.)