We will be discussing smart pointers, but you need another
pointer assignment before we deal with this language improvement.
It is important to gain a grasp of pointers for at least two reasons.
While much of the pressure to use pointers is relieved by the STL/SCL, there are still some situations where basic pointers are required.
If you claim training in c++, people will expect that you have some knowledge in this area.
There are others who's training have provided NO knowledge in this area.
If you want to work in areas such as operating systems, compilers, programming languages, architecture or cyber security, knowledge of pointers is REQUIRED.
It is also useful to understand the failing of "raw" pointers when discussing the safer pointer types.
Read his warnings in gray boxes throughout this section.
the first one says use low-level memory operations as little as possible.
Work through diagrams for the following
int a;
int *a = new int;
int **a = new int*;
*a = new int;
What is the stack?
What is the heap?
When is memory allocated on each?
What is the default value for a pointer?
What value should pointers be initialized to?
When should pointers be initialized?
What does new do?
there is a c function void * malloc(size_t size)
malloc allocates n bytes on the heap.
And returns a pointer to that memory.
New on the other hand
Allocates the memory
If the item being allocated is an object (class or struct), the constructor is called (if there is one)
There is a c function free(void * ptr)
Just like delete.
But delete calls the object's destructor if it exists.
And free does not.
new type[size]
Calls the constructor for each element of the array
delete [] itemptr calls all the destructors if they exist.
He points out
Every new should have a delete
Every new[] should have a delete[]
Don't mix the two.
After a delete, set the pointer back to nullptr.
Memory Allocation Fails
When the heap becomes full, new will fail.
By default it will cause an exception.
Which will cause your program to crash if you don't catch it.
We will learn about exceptions before the semester is over.
But for now, if your program trys to allocate memory and fails, exiting is probably the best you can do.
But what if you are running a huge computation and we don't get far enough?
Read about exception handlers.
int *ptr = new(nothrow) int;
This will return nullptr
And you can take some action to
Save the state of your computation.
Free up memory.
How do arrays work?
Draw a picture for each
int data[10];
int *moreData = new int[10];
int bigdata[10][5];