Item 22. Exception-Safe Class Design, Part 1: Copy Assignment

I l @ ve RuBoard

Difficulty: 7

Is it possible to make any C++ class strongly exception-safe, for example, for its copy assignment operator? If so, how? What are the issues and consequences? To illustrate , this Item explains and then solves the Cargill Widget Example.

  1. What are the three common levels of exception safety? Briefly explain each one and why it is important.

  2. What is the canonical form of strongly exception-safe copy assignment?

  3. Consider the following class:

     // Example 22-1: The Cargill Widget Example // class Widget { public:   Widget& operator=( const Widget& ); // ???       // ... private:   T1 t1_;   T2 t2_; }; 

    Assume that any T1 or T2 operation might throw. Without changing the structure of the class, is it possible to write a strongly exception-safe Widget::operator= ( const Widget& ) ? Why or why not? Draw conclusions.

  4. Describe and demonstrate a simple transformation that works on any class in order to make (nearly) strongly exception-safe copy assignment possible and easy for that class. Where have we seen this transformation technique before in other contexts?

I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net