I l@ve RuBoard Previous Section Next Section

Item 19. Code Complexity桺art 2

Difficulty: 7

The challenge: Take the three-line function from Item 18 and make it exception-safe. This exercise illustrates some important lessons about exception safety.

Is the function from Item 18 exception-safe (works properly in the presence of exceptions) and exception-neutral (propagates all exceptions to the caller)?



String EvaluateSalaryAndReturnName( Employee e ) 


{


  if( e.Title() == "CEO" || e.Salary() > 100000 )


  {


    cout << e.First() << " " << e.Last() << " is overpaid" << endl;


  }


  return e.First() + " " + e.Last();


}


Explain your answer. If it is exception-safe, does it support the basic guarantee, the strong guarantee, or the nothrow guarantee? If not, how must it be changed to support one of these guarantees?

Assume that all called functions are strongly exception-safe (might throw but do not have side effects if they do throw), and that any objects being used, including temporaries, are exception-safe (clean up their resources when destroyed).

To recap the basic, strong, and nothrow guarantees, see Item 11. In brief, the basic guarantee ensures destructibility and no leaks; the strong guarantee, in addition, ensures full commit-or-rollback semantics; and the nothrow guarantee ensures that a function will not emit an exception.

    I l@ve RuBoard Previous Section Next Section