Sobes.tech
Middle

What are the two types of delete operators in C++?

sobes.tech AI

Answer from AI

  1. The regular delete operator: Used to free memory allocated for a single object using the new operator.
  2. The delete[] operator: Used to free memory allocated for an array of objects using the new[] operator. When using delete[], 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;