Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          unique-pointers-1/p1.cc - Unique_ptr versus raw pointer.Lecture 4 - slide 16 : 40
Program 3

// RUN IT to see normal return of f, early return of f, and exception thrown in f. 
// q in f is destroyed in all cases (normal return, exception, early return)
// p in f is only destroyed upon normal return. *p is leaked upon early return and upon exeception.
// Inspired from Stroustrup 4ed, page 112.

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

class SomeProblem{};

void f(int i){
  Point *p {new Point{1,2}};                      // p is a raw pointer to a new point
  std::unique_ptr<Point> q{new Point{3,4}};       // q is a unique_ptr to a new point

  if (i == 10) throw SomeProblem{};               // In some cases, an exception is thrown
  if (i == 11) return;                            // In some cases, we have an early return

  p->displace(1,1);
  q->displace(1,1);

  delete p;
}

int main(){
  int i;
  std::cout <<  "Enter i: "; 
  std::cin >> i;

  try{
    f(i);
  }
  catch(SomeProblem){
    std::cout << "Some Problem" << std::endl;
  }
}