首页 > 其他 > 详细

析构函数的调用与return语句

时间:2018-09-28 13:33:20      阅读:178      评论:0      收藏:0      [点我收藏+]

老师在课堂上讲到了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;
}

程序运行结果:

技术分享图片

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

析构函数的调用与return语句

原文:https://www.cnblogs.com/lsh99k/p/9718009.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!