Middle
What are the two types of delete operators in C++?
sobes.tech AI
Answer from AI
- The regular
deleteoperator: Used to free memory allocated for a single object using thenewoperator. - The
delete[]operator: Used to free memory allocated for an array of objects using thenew[]operator. When usingdelete[], destructors are called for all elements of the array in reverse order of their creation.
Using the wrong type of delete operator (for example, delete for an array or delete[] for a single object) leads to undefined behavior.
Example:
// Regular delete operator
int* single_object = new int(10);
// ... use single_object
delete single_object;
// delete[] operator for array
int* array_of_objects = new int[5];
// ... use array_of_objects
delete[] array_of_objects;