Programming in C++

Exercise Sheet 10
  1. This is a paper exercise.

    The principles of exception handling require that an exception handler must do only one of the following:

    1. clean up (eg close open files) and re-throw (or exit with error)
      (Not needed if you're using RAII!!!)
    2. or attempt to rectify original cause and ensure that try block is re-executed
    3. or attempt to achieve same effect as the try block in some other way

    Sketch examples in C++ syntax.

  2. Experiment with local allocation and exceptions:
    1. Write a little class with a constructor that stores some information in a field and a destructor that prints out that information.
    2. Declare an object of this class inside a block and check that it is destroyed when you expect.
    3. Throw an exception (define your own trivial one) inside the block and catch it outside, and check that your object is destroyed.

  3. Consider the following code fragment:
            class Node {  
                    Table *table;  
                    Name *name;  
     
            public:  
                    Node(const char *n) :  
                            table(new Table()), name(new Name(n)) {}  
     
                    // ...  
            };

    Rewrite this using auto_ptrs to avoid the need for a destructor. Does this mean you don’t need a copy constructor or an assignment operator? (You’ll need to read the auto_ptr class to answer this.)

  4. (harder, and optional) How would you modify the auto_ptr class to create a new one (smart_ptr) that keeps a count of the number of uses of each pointer, so that it is deleted only when this count falls to zero?
    Hint: You will need to place the pointer and reference count together in an auxiliary class, and make your new smart_ptr point at that.

    You can include the auto_ptr class by saying

            #include <memory>

  5. Would the smart pointer of the previous section work with doubly linked lists?