$\require{cancel}$
Your New Friend new
and their Partner delete
The real strength of a pointer is the ability to deal with dynamic memory.
This is memory allocated from the heap.
BUT FIRST
- Pointers are ALWAYS either pointing at something or at
nullptr
- If a pointer is pointing at something it MUST be valid memory.
- Before we access the thing a pointer is pointing to we MUST check to make sure it is not
nullptr
.
The following are common errors:
- Dereferencing
nullptr
... crashety crash crash.
- Accessing memory that is no longer allocated.
- Instant crash if you are very lucky.
- Delayed crash if you lucky
- Program running with bad data, bad results, hard to find bug
- No ipact (rare in the long run)
- Accessing memory that was not allocated
When you allocate memory
- Delete it when you are finished.
- Delete it only once.
- Use the proper form of delete.
- For us, all memory must be deallocated at exit.
new
and new[]
- Allocate the correct amount of memory off the heap.
- Based on the size of the data type
- And the number of elements requested in the case of
new[]
- The class constructor will be called for all allocated objects.
- Return a pointer to that element type.
- Upon failure it will return
nullptr
-
T* new T {initializer}
-
T* new T[int] {initializer}
- I generally do not use the initializer.
- It can be more complex, but we will use these forms.
- reference.
delete
and delete[]
- Reference.
- Returns memory to the heap.
- DOES NOT change the variable.
- no return value .
-
void delete pointervalue
-
void delete[] pointervalue
Simple memory allocation demo array.cpp.