☜
☞
Operators delete and delete[]
The delete and delete[] operators in C++ are used for deallocating memory that was previously allocated using the new and new[] operators, respectively. Here's a detailed look at each:
delete Operator
- Purpose: The delete operator is used to free the memory that was allocated for a single object.
- Syntax:
int* ptr = new int; // Allocates memory for a single int
delete ptr; // Deallocates memory
- Behavior: When you use delete, the destructor for the object (if any) is called, and the memory is then freed. It's important to only use delete on memory allocated with new.
delete[] Operator
- Purpose: The delete[] operator is used to free memory that was allocated for an array of objects.
- Syntax:
int* arr = new int[10]; // Allocates memory for an array of 10 ints
delete[] arr; // Deallocates memory
- Behavior: When delete[] is used, the destructors for all the elements in the array are called (if the elements are objects with destructors), and then the memory is freed. It's crucial to match new[] with delete[].
Key Differences
Object vs. Array:
- Use delete when you've allocated a single object with new.
- Use delete[] when you've allocated an array of objects with new[].
Destructor Calls:
- delete calls the destructor for the single object.
- delete[] calls the destructors for each object in the array.
Example
class MyClass {
public:
MyClass() { std::cout << "Constructor called\n"; }
~MyClass() { std::cout << "Destructor called\n"; }
};
int main() {
MyClass* singleObject = new MyClass; // Allocates a single object
delete singleObject; // Correct: Calls destructor for the single object
MyClass* objectArray = new MyClass[3]; // Allocates an array of 3 objects
delete[] objectArray; // Correct: Calls destructor for each object in the array
}
Summary
- delete: Use it to deallocate memory for a single object created with new.
- delete[]: Use it to deallocate memory for an array of objects created with new[].
Always ensure that delete is matched with new and delete[] is matched with new[] to avoid undefined behavior, which could lead to memory leaks or crashes.
☜
☞