Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
A variant of the shared_ptr program


Here is my solution:

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

using namespace std;

void f(shared_ptr<Point> pp1){
  shared_ptr<Point>ap1(pp1),               // Now two references to (1,2)
                   ap2(new Point(3,4));

  cout << "ap1: " << *ap1 << endl;   
  cout << "ap2: " << *ap2 << endl;   

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

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

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

  ap2 = ap1;                          // Now three reference to (1,2).
                                      // ap2 (3,4) is deleted here (the one and only reference is gone!)
                                     
  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 go out of scope.
  // But there is still a reference to (1,2) - from the copy of the shared pointer in main.
}

int main(){
  shared_ptr<Point>p(new Point(1,2));
  f(p);

  // (1,2) is still alive here!

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

The program output is:

ap1: (1,2)
ap2: (3,4)
ap2: (4,5)
ap1-ap2 dist: 4.24264
Now assigning ap1 to ap2
Point deleted
ap1: (1,2)
ap2: (1,2)
p: (1,2)
Point deleted