Things To Remember:Constructors, Destructors, and Assignment Operators

王朝other·作者佚名  2006-01-31
宽屏版  字体: |||超大  

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有