Things To Remember:Constructors, Destructors, and Assignment Operators

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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值