Operators new and new[]
In C++, delete and delete[] are used to deallocate memory that was previously allocated using new and new[], respectively. Here's a breakdown of their usage and differences:
delete
- Purpose: delete is used to free memory that was allocated for a single object using new.
- Syntax:
int* ptr = new int; // Allocates memory for a single int
delete ptr; // Deallocates memory
- Behavior: When you use delete, the destructor of the object (if it has one) is called, and then the memory is freed.
delete[]
- Purpose: delete[] is used to free memory that was allocated for an array of objects using new[].
- Syntax:
int* arr = new int[10]; // Allocates memory for an array of 10 ints
delete[] arr; // Deallocates memory
- Behavior: When you use delete[], the destructors for all elements in the array are called (if they have destructors), and then the memory is freed.
Key Differences
Object vs. Array: Use delete for a single object and delete[] for an array of objects. If you use delete on a pointer that was allocated with new[], or vice versa, the behavior is undefined, which can lead to runtime errors.
Destructors: delete calls the destructor for a single object, while delete[] calls destructors for all elements in the array.
Example
class MyClass {
public:
MyClass() { std::cout << "Constructor called\n"; }
~MyClass() { std::cout << "Destructor called\n"; }
};
int main() {
MyClass* obj = new MyClass; // Allocate memory for a single object
delete obj; // Correct: Calls MyClass destructor once
MyClass* arr = new MyClass[3]; // Allocate memory for an array of 3 objects
delete[] arr; // Correct: Calls MyClass destructor 3 times
}
In this example, the destructor is called for each object when delete or delete[] is used.
Understanding when to use delete vs. delete[] is crucial for managing dynamic memory correctly in C++.