Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          unique-pointers/raw-ptr1.cc - An illustration of raw pointers.Lecture 4 - slide 15 : 40
Program 3

// Programming with C-style, raw pointers to Point, before we illustrate the use of smart pointers.

#include <memory>
#include <iostream>
#include <string>
#include "point.h"

using namespace std;

void f(Point *pp1){
  Point *ap1{pp1},                     // Copy pointer to ap1
        *ap2{new Point(3,4)};          // Allocate second point here. ap2 points to it.

  // Do something...
  cout << "ap1: " << *ap1 << endl;     // (1,2)
  cout << "ap2: " << *ap2 << endl;     // (3,4)

  ap2->displace(1,1);
  cout << "ap2: " << *ap2 << endl;     // (4,5)

  cout << "ap1-ap2 dist: " << ap1->distance_to(*ap2) << endl;  // 4.24264

  ap2 = ap1;                           // Copy a pointer. (3,4) is lost here.

  // Print ap1 and ap2
  if (ap1)                             // (1,2)
     cout << "ap1: " << *ap1 << endl;  
  else
     cout << "ap1 is nullptr" << endl;

  if (ap2)                             // (1,2)
     cout << "ap2: " << *ap2 << endl;
  else
     cout << "ap2 is nullptr" << endl;

  // Both points survive on the heap. Memory for (3,4) leaks!
}

int main(){
  Point *p = new Point(1,2);           // Allocate first point here
  f(p);                                // Pass pointer to (1,2) to f.

  cout << "p: " << *p << endl; // (1,2)
}