NOTE:
These are a little sketchy...I'll fill in details 'soon'.
heap memory is requested in C++ with the new operator:
type *pvar; pvar = new type; // ask OS for a type-sized memory area from the // heap -- stores address into pvar
You can also augment this with a constructor call placed after the type:
type *pvar; pvar = new type(parameters); // construct space specifically rather // than by default
can also request arrays of space instead of single objects:
type *parr; parr = new type [size]; // ask OS for an array of size elements // of data-type type from heap -- store // address of first element in parr
size here can be any integer-valued expression — not limited to literals and constants anymore!
when done with heap memory, give it back with the delete operator:
delete pvar; // relinquishes heap object pointed to by pvar delete [] parr; // relinquishes entire heap array pointed to by parr
Whatever you do don't mix delete with new[] or vice-versa! They have different ways of storing memory information and this can cause quite the corruption!
sometimes allocation (space request) fails; OS will return invalid address known as nullptr:
pvar = new type; if (pvar == nullptr) { // allocation failed...cannot access heap memory } else { // allocation successful...access heap memory at will } delete pvar; // relinquish memory when done pvar = nullptr; // remind ourselves that pvar is no longer valid to use
Note that it is alright now to delete nullptr. This was once illegal and lots of web advice will still tell you this. But it is now fine!
access to heap data — in the else branch above — is done through dereferencing:
*pvar = 4; // stores 4 in location pointed to by pvar cout << *pvar; // prints value in location pointed to by pvar cin >> *pvar; // reads value into location pointed to by pvar *parr = 9; // stores 9 in first element of array pointed to by parr cout << *parr; // prints value in first element of array // pointed to by parr cin >> *parr; // reads value into first element of array // pointed to by parr parr[2] = 12; // stores 12 in 3rd element of array pointed to by parr cout << parr[2]; // prints value in 3rd element of array // pointed to by parr cin >> parr[2]; // reads value into 3rd element of array // pointed to by parr