Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          shared-pointers/shared-ptr1.cc - An illustration of shared_ptr<Point> - same example as for unique_ptr<Point>.Lecture 4 - slide 12 : 35
Program 7

// Same example as for unique_ptr, just using shared_ptr instead

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

using namespace std;

void f(Point *pp1){
  shared_ptr<Point>ap1(pp1),
                   ap2(new Point(3,4));

  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

  cout << "Now assigning ap1 to ap2" << endl;

  // Normal copying assignment:   The point referred by ap2 (3,4) is deleted here.
  //                              The pointer encapsulated in ap1 is copied to ap2.
  ap2 = ap1;                      // Now both ap1 and ap2 points at (1,2)
                                     
  if (ap1.get())                        // (1,2)
     cout << "ap1: " << *ap1 << endl;  
  else
     cout << "ap1 is nullptr" << endl;

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

  // ap1 and ap2 goes out of scope
  // The point (1,2) is deleted here.
}

int main(){
  Point *p = new Point(1,2);
  f(p);

  cout << "p: " << *p << endl; // Unsafe! 
                               // p has been deleted by exit from f.
}