Destructor role in C++ - Time & Space Complexity
We want to understand how the time cost of a destructor grows as the program runs.
Specifically, how the destructor's work changes when cleaning up objects.
Analyze the time complexity of this destructor code.
class MyClass {
std::string* data;
int size;
public:
MyClass(int n) : size(n) { data = new std::string[size]; }
~MyClass() { delete[] data; }
};
This code creates an array and the destructor frees that array when the object is destroyed.
Look at what the destructor does repeatedly.
- Primary operation: Deleting an array of size n.
- How many times: Once per object destruction, but the delete[] frees all elements.
The destructor frees memory proportional to the array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to free |
| 100 | About 100 steps to free |
| 1000 | About 1000 steps to free |
Pattern observation: The work grows directly with the size of the array.
Time Complexity: O(n)
This means the destructor takes longer if the array it frees is bigger, growing in a straight line with size.
[X] Wrong: "Destructor runs instantly no matter the data size."
[OK] Correct: The destructor must free all allocated memory, so if the data is large, it takes more time.
Knowing how destructors scale helps you write efficient cleanup code and understand program performance better.
"What if the destructor also had to delete multiple arrays inside the object? How would the time complexity change?"