Item 9. Writing Exception-Safe
Code—Part 2
Difficulty: 8
Now that we have the
default constructor and the destructor under our belts, we might be
tempted to think that all the other functions will be about the
same. Well, writing exception-safe and exception-neutral copy and
assignment code presents its own challenges, as we shall now
see.
Consider again Cargill's Stack
template:
template <class T> class Stack
{
public:
Stack();
~Stack();
Stack(const Stack&);
Stack& operator=(const Stack&);
/*...*/
private:
T* v_; // ptr to a memory area big
size_t vsize_; // enough for 'vsize_' T's
size_t vused_; // # of T's actually in use
};
Now write the Stack copy constructor
and copy assignment operator so that both are demonstrably
exception-safe (work properly in the presence of exceptions) and
exception-neutral (propagate all exceptions to the caller, without
causing integrity problems in a Stack object).
|