By Scott Meyers Things to Remember Constructors, Destructors, and Assignment Operators· Compilers may implicitly generate a class's default constructor, copy constructor, copy assignment operator, and destructor. · To disallow functionality automatically provided by compilers, declare the corresponding member functions private and give no implementations. Using a base class like Uncopyable is one way to do this. · Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should have a virtual destructor. · Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors. · Destructors should never emit exceptions. If functions called in a destructor may throw, the destructor should catch any exceptions, then swallow them or terminate the program. · If class clients need to be able to react to exceptions thrown during an operation, the class should provide a regular (i.e., non-destructor) function that performs the operation. · Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor. · Have assignment operators return a reference to *this. · Make sure operator= is well-behaved when an object is assigned to itself. Techniques include comparing addresses of source and target objects, careful statement ordering, and copy-and-swap. · Make sure that any function operating on more than one object behaves correctly if two or more of the objects are the same. · Copying functions should be sure to copy all of an object's data members and all of its base class parts. · Don't try to implement one of the copying functions in terms of the other. Instead, put common functionality in a third function that both call.
|