destructor Rule And Sequence 【C++ primer】

本文探讨了C++中析构函数、拷贝构造函数及赋值操作符之间的紧密联系,即所谓的“Rule of Three”。文章指出,如果一个类需要自定义析构函数,则通常也需要自定义拷贝构造函数和赋值操作符。此外,文中还解释了即使定义了自己的析构函数,编译器合成的析构函数也会被执行的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

A useful rule of thumb is that if a class needs a destructor, it will also need the assignment operator and a copy constructor. This rule is often referred to as the Rule of Three , indicating  that if you need a destructor, then you need all three copycontrol members.

 

An important difference between the destructor and the copy constructor or assignment operator is that even if we write our own destructor, the synthesized destructor is still run .

 

 

class Sales_item {

public:

// empty; no work to do other than destroying the members,

// which happens automatically

~Sales_item() { }

// other members as before

};

 

When objects of type Sales_item are destroyed, this destructor, which does nothing, would be run. After it completes, the synthesized destructor would also be run to destroy the members of the class. The synthesized destructor destroys the string member by calling the string destructor, which frees the memory used to hold the isbn . The units_sold and revenue members are of built-in type, so the synthesized destructor does nothing to destroy them.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值