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 unique_ptr program


Here is my solution:

// Variation of unique-ptr-1.cc

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

using namespace std;

unique_ptr<Point> f(unique_ptr<Point> pp1){   // Notice the new signature.
  unique_ptr<Point>ap1(move(pp1)),      // Cannot copy unique_ptr. Cast to rvalue by move.  
                   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; 

  // Destructive copying:  The point referred by ap2 is deleted.
  //                       The pointer encapsualated in ap1 is moved to ap2.
  //                       ap1 is unbound (becomes nullptr).
  cout << "Now assigning ap1 to ap2" << endl;
  ap2 = move(ap1);        

  if (ap1.get())                        // ap1 is nullptr
     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;

  return ap2;        // ap2 is moved out of f.
}

int main(){
  unique_ptr<Point> p(new Point(1,2));
  p = f(move(p));   // notice move

  cout << "p: " << *p << endl; // Now OK. (1,2).
                               // p is moved back from f.
}

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 is nullptr
ap2: (1,2)
p: (1,2)
Point deleted

Notice that we manage to move the point (1,2) back to main, and that this version of the program does not fail, as did the original program just before the end of main.