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

被折叠的 条评论
为什么被折叠?



