1. Features
- A member function of the class
- The name consists of a tilde followed by the class name
- No return value
- Does not accept parameters
- Can not be overloaded, for a given class, there will only be one destructor
class Foo{
public:
~Foo();
}
2. Several important features of destructor
- The body of the destructor itself does not directly destroy the members
- The member is destroyed in the implicit destructuring phase of the compiler after the destructor body
- The destructor first executes the function body, and then destroys the members in the reverse order of member initialization.
3. When to call the destructor
- Whenever an object is destroyed, its destructor is automatically called
- The variable is destroyed when it leaves its scope.
- When an object is destroyed, its members will also be destroyed.
- When the container (whether it is a standard container or an array) is destroyed, its elements will also be destroyed.
- For dynamically allocated objects, the operator is destroyed when the pointer to it refers to delete.
- For temporary objects, they are destroyed when the complete expression that created it ends.
//新的局部作用域
{
Sales_data *p = new Sales_data();
auto p2 = make_shared<Sales_data>();
Sales_data item(*p);
vector<Sales_data> vec;
vec.push_back(*p2);
delete p; //对p指向的对象执行析构函数
} //退出局部作用域,对p2,item,vec,调用析构函数
//销毁p2会递减其引用计数,如果引用计数变为0,对象被释放
//销毁vec,也会将其内部的元素销毁
4. Synthesized destructor
When a class does not define its own destructor, the compiler will define a synthetic destructor for it. The body of the synthetic destructor is empty.