How is the C++ destructor function invoked?

The C++ destructor is automatically called when an object is destroyed, without the need for manual invocation. The destructor is automatically called when the object’s lifetime ends, such as when the object goes out of scope, the delete operator is used to release dynamically allocated objects, or when the program terminates.

Here is an example:

#include <iostream>
using namespace std;

class MyClass {
public:
    MyClass() {
        cout << "构造函数被调用" << endl;
    }

    ~MyClass() {
        cout << "析构函数被调用" << endl;
    }
};

int main() {
    MyClass obj; // 创建一个对象
    // 对象超出作用域,析构函数会被自动调用

    return 0;
}

Output:

构造函数被调用
析构函数被调用

In the example above, the destructor function will be automatically called when the object obj goes out of scope, resulting in the output “Destructor called”.

bannerAds