Back to slide -- Keyboard shortcut: 'u'                      free-store/new-del-1.cpp - Illustration of free store.Lecture 3 - slide 15 : 27
Program 1

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

using namespace std;

int main(){

  // Allocate and delete an int on the free store:
  int *pi = new int{};           // Allocate space to an int, which is initialized to 0.
  *pi = *pi + 5;                 // *pi is 5 (because it was default initialized when created).
  cout << 6 * *pi << endl;       // 30
  delete pi;                     // Deallocate the int


  // Allocate and delete an array of ints on the free store:
  int *ia = new int[10];         // Allocate an array of 10 ints
  for(int i = 0; i < 10; i++)    // Initialize array
     ia[i] = 2 * i;              // ... by assigning to its elements.

  for(int i = 0; i < 10; i++)    
    cout  << setw(3) << ia[i];   // 0  2  4  6  8 10 12 14 16 18        setw is a stream manipulator.
  cout << endl;

  delete [] ia;                  // Deallocate the array


  // Allocate and delete a vector of ints on the free store:
  vector<int> *vd = 
      new vector<int>(10);       // Allocate a vector

  for(int i = 0; i < 5; i++)     // Mutate half of the vecctor  
    (*vd)[i] = 2 * i;

  for(int i = 0; i < 10; i++)    
    cout << setw(3) << (*vd)[i]; // 0  2  4  6  8  0  0  0  0  0

  cout << endl;

  delete vd;                     // Deallocate the vector

}