【发布时间】: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