Chapter 14. Writing Exception-Safe Code—Part 7

Difficulty: 5

Only a slight variant—of course, operator=() is still very nifty.

Imagine that the /*????*/ comment in StackImpl stood for public. Implement all the member functions of the following version of Stack, which is to be implemented in terms of StackImpl by using a StackImpl member object.

template <class T> 
class Stack
{
public:
  Stack(size_t size=0);
  ~Stack();
  Stack(const Stack&);
  Stack& operator=(const Stack&);
  size_t Count() const;
  void   Push(const T&);
  T&     Top();   // if empty, throws exception
  void   Pop();   // if empty, throws exception
private:
  StackImpl<T> impl_;  // private implementation
};

Don't forget exception safety.

Solution

This implementation of Stack is only slightly different from ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.