Junior — Middle
What is the difference between the delete operator and the delete[] operator when freeing memory in C++?
sobes.tech AI
Answer from AI
In C++, the delete operator is used to free memory allocated for a single object, while the delete[] operator is used to free memory allocated for an array of objects.
Main differences:
deletecalls the destructor for a single object and frees the memory.delete[]calls destructors for all elements of the array and then frees the memory.
Using delete for an array will only call the destructor for the first element, which can lead to resource leaks or incorrect behavior.
Example:
int* p = new int[5];
// ...
delete[] p; // correct
int* q = new int;
// ...
delete q; // correct
Always use the appropriate operator for correct memory deallocation.