为什么同一个类对象的构造函数和析构函数被隐式调用多次

问题描述

英语不是我的母语,所以请原谅我的语法问题。

我在运行我的程序时,发现在定义对象和显式调用构造函数时都会调用类构造函数调用构造函数后离开作用域后,析构函数调用了两次。

#include<iostream>
class test {
private:
    int a;
    int b;
    int c;
public:
    test(int first = 0,int second = 0,int third=0 );
    void show();
    ~test();
};

void test::show() {
    std::cout << this->a<<"\n";
}
test::test(int first,int second,int third ) {
    this->a = first;
    this->b = second;
    this->c = third;
    std::cout << "Construct\n";
}
test::~test() { std::cout << "destruct\n"; }

extern test myclassone;
#include <iostream>
#include "myhead.h"

test myclassone;
int main()
{
    std::cout << "begain\n";
    {
        std::cout << "mid\n";
        myclassone = test(1,1,1);
        std::cout << "mid\n";
        myclassone.show();
    }
    std::cout << "end\n";
}

这个程序的输出

Construct
begain
mid
Construct
destruct
mid
1
end
destruct

在我的期望中,构造函数和析构函数只会被调用一次。但令人费解的是,根据输出,它们被调用了两次。 我google了这个问题,很多答案都没有解释为什么在定义对象时调用构造函数,为什么在调用构造函数后立即调用析构函数

解决方法

您的程序运行如下:

  1. 为全局对象 test myclassone; 调用构造函数。
  2. main() 被调用。
  3. begainmid 被打印出来。
  4. 为时态对象 test(1,1,1) 调用构造函数。
  5. 临时对象被分配给全局对象。
  6. 为时态对象 test(1,1) 调用析构函数。
  7. mid 已打印。
  8. myclassone.show() 被调用。
  9. end 已打印。
  10. main()返回。
  11. 为全局对象 test myclassone; 调用析构函数

因此构造函数和析构函数为每个对象调用一次,总共调用两次。