Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

For a dynamically allocated object, these two stages are typically handled automatically by using the new and delete operators. The expression new T for a type T results in a call to operator new() to allocate sufficient memory for T. If memory is successfully allocated, the default constructor for T is called. The result of the expression is a pointer P to the object of type T. When that pointer is passed in the expression delete P, it results in a call to the destructor for T. After the destructor completes, a call is made to operator delete() to deallocate the memory.

When a program creates a dynamically allocated object is created by means other than a call to the new operator, it is said to be manually managing the lifetime of that object. This situation arises when using other allocation schemes to obtain storage for the dynamically allocated object, such as using an allocator object or malloc(). For instance, a custom container class may allocate a slab of memory in a reserve() function in which subsequent objects will be stored. See MEM51-CPP. Properly deallocate dynamically allocated resources for further information on dynamic memory management as well as MEM08-CPP. Use new and delete rather than raw memory allocation and deallocation.

...