//exc_asg1.cpp
/*************************************************************************
File: exc_asg1.cpp
Description: This file contains a solution for the template assignment. It
   uses a managed pointer to assure that the String objects are deleted
   on function exit (normal and abnormal). It also uses a try/catch block
   to allow the program to complete.
Source(s):
Course Section: Advanced C++ Basics, Templates
Author: j. stafford
Date: 970121
*************************************************************************/
#include <iostream.h>
class String {
public:
   String() {
      cout << "String<" << this << ">::String()" << endl; count_++; }
   ~String() {
      cout << "String<" << this << ">::~String()" << endl; count_--;}
   static int count() { return count_; }
private:
   String(const String&);
   String& operator=(const String&);
   static int count_;
};
int String::count_=0;
template <class T> class Ptr {
public:
   Ptr(T *ptr) : ptr_(ptr) {}
   ~Ptr() { delete ptr_; }
private:   T *ptr_;
};
class Book {
public:
   Book(int flag) :author(new String) , description(new String) {
      cout << "Book<" << this << ">::Book()" << endl;
      //some kind of error
      if (flag) throw 0;
   }
   ~Book() {
      cout << "Book<" << this << ">::~Book()" << endl;
//      delete author;
//      delete description;
   }
private:
   Book(const Book&);
   Book& operator=(const Book&);
   String name;
   Ptr<String> author;      //String *author;
   Ptr<String> description; //String *description;
};
main() {
   try {
   Book b1(0);
   } catch (...) {}
   try {
   Book b2(1);
   } catch (...) {}
   if (String::count())
      cerr << "error, String::count() = " << String::count() << endl;
   else
      cout << "no errors";
   return String::count();
}
//end of file

