【问题标题】:why the constructor and destructor of the same class object are implicitly called multiple times为什么同一个类对象的构造函数和析构函数被隐式调用多次
【发布时间】:2021-09-03 06:32:21
【问题描述】:

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

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

#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了,很多答案都没有解释为什么在定义对象的时候调用构造函数,为什么在调用构造函数后立即调用析构函数

【问题讨论】:

  • 一个用于您的全局test myclassone,另一个用于您的临时test(1,1,1)
  • 在调试模式下编译代码并在构造函数和析构函数上放置断点会很有启发性。调用堆栈的状态会告诉你你在哪里以及为什么创建了对 con/destructor 的调用。
  • 我看不出你有什么理由为你的英语道歉。我见过以母语为母语的人做得更糟。
  • 关键是每个构造函数调用都会有一个析构函数调用。如果您看到的析构函数调用比您预期的要多,这几乎总是意味着您在某个地方忽略了构造函数。

标签: c++ c++11 constructor destructor


【解决方案1】:

你的程序运行如下:

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

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

【讨论】:

  • @KennyOstrom 谢谢,已修复。
  • 更改构造函数的“日志”输出有助于了解发生了什么:std::cout &lt;&lt; "Construct\n" &lt;&lt; a &lt;&lt; " " &lt;&lt; b &lt;&lt; " " &lt;&lt; c &lt;&lt; std::endl; 将显示 default 构造函数被调用一次,显式构造函数被调用一次。
猜你喜欢
  • 2015-04-28
  • 2013-12-11
  • 2015-10-09
  • 2022-07-05
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2021-04-01
相关资源
最近更新 更多