Demystifying C++ - New and Delete Operators

From emmtrix Wiki
Jump to navigation Jump to search

In C++, the new operator is used to dynamically allocate memory and call the object's constructor, while the delete operator is used to call the destructor and subsequently free the memory. These operators significantly simplify memory management in C++ and reduce the likelihood of errors that often occur with manual memory management.

In the equivalent C code, memory is allocated or released via the global operator new and operator delete functions. The implementation of both functions is found in libc++ and uses malloc and free respectively.

new
C1* obj = new C1();
struct C1* obj = (struct C1*)::operator new(sizeof(C1));
if (obj) {
  C1_ctor_complete(obj);
}
delete
delete obj;
if (obj) {
  C1_dtor_complete(obj);
  ::operator delete(obj);
}

The code generated by new/delete can become quite complex, for instance, when allocating or deallocating an array. In such cases, sometimes intricate loops for constructor and destructor handling are created.