析构函数的调用与return语句

老师在课堂上讲到了return语句在执行时会自动调用对象的析构函数。我编写了下述代码测试发现整个程序析构函数调用次数与构造函数不等,这样难道不会产生内存泄漏吗?

源代码如下:

#include <iostream>
using namespace std;

class A {
public:
    A(int i = 1) :x(i){ cout << "constructed." << endl; }
    ~A() { cout << "destructed." << endl; }
    int get_x() { return x; }
private:
    int x;
};

int aqr_it(A a) {
    A b=a;
    return (b.get_x())*(b.get_x());
}

int main() {
    A a;
    cout << a.get_x() << endl;
    cout << aqr_it(a) << endl;
    return 0;
}

程序运行结果:

暂时不知道如何解释该现象。

猜你喜欢

转载自www.cnblogs.com/lsh99k/p/9718009.html