You can control the allocation and deallocation of memory in a program for objects and for arrays of any built-in or user-defined type. This is known as dynamic memory management and is performed with the operators new and delete. We’ll use these capabilities to implement our Array
class in the next section.
You can use the new
operator to dynamically allocate (i.e., reserve) the exact amount of memory required to hold an object or built-in array at execution time. The object or built-in array is created in the free store (also called the heap)—a region of memory assigned to each program for storing dynamically allocated objects.2 Once memory is allocated in the free store, you can access it via the pointer that operator new
returns. When you no longer need the memory, you can return it to the free store by using the delete
operator to deallocate (i.e., release) the memory, which can then be reused by future new
operations.3
2. Operator new
could fail to obtain the needed memory, in which case a bad_alloc
exception will occur. Chapter 17 shows how to deal with failures when using new
.
3. Operators new
and delete
can be overloaded, but this is beyond the scope of the book. If you do overload new
, then you should overload delete
in the same scope to avoid subtle dynamic memory management errors.