More Effective C++ book notes

abnormal

Use destructors to avoid leaking resources

Save an object in a resource that must be automatically freed and rely on the object’s destructor release to avoid exceptions. For example, the smart pointer auto_ptr can be used to point to the created object to achieve this design.

Stop resource leaks in constructors.

This article describes how to handle resource leaks caused by an exception in a constructor by using an auto_ptr instead of a pointer class Members object without manually releasing resources in the destructor.

Exceptions are forbidden outside of destructors

Understanding: Discusses two reasons why an exception that occurs in a destructor must be caught in its function:

  • (1) It prevents terminate from being called in the stack-unwinding mechanism during exceptions propagation. If control leaves destructor based on an exception element while another exception is in effect, c++ calls terminate.
  • (2) Make sure destructor does everything it’s supposed to do.

Understand the difference between “throwing an exception” and “passing an argument” or “calling a virtual function.”

Understanding: There are three main differences

  • (1) Exception objects are always copied, twice if captured by value.
  • (2) Objects “thrown as exceptions” allow fewer type conversions than objects “passed to functions”. The exception/catch clause supports only two types of conversion. One is to inherit the class conversion (base class can catch subclasses), and the other is to convert a typed pointer to a typed pointer (catch clause for const void* Pointers). Can catch any pointer type exception).
  • (3) The matching mechanism of catch clause is “first fit”.

Catch exceptions by reference

The advantages and disadvantages of passing an exception to a catch are discussed in three ways: by pointer, by value and by reference. Finally, the conclusion is drawn that by reference is used.

  • * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  • (2) There will be cutting problems in by value mode. That is, if the base class captures the exception object of the subclass, the derived component of the subclass will be lost. In fact, it will become the object of the subclass. When a virtual function is called, only functions of the base class are called, not those of a subclass.

Use Exception Spectifications wisely

解 析 : Exceptions specifications are not good.

Understand the cost of exception handling

To understand:

  • The compiler does not support exception whenever it can.
  • Try blocks and exception Specification may not be used because that would inflate the code.