为什么析构函数调用比构造函数调用多
我正在测试以下代码,让我感到困惑的是析构函数调用比构造函数调用多:
#include <iostream>
struct A {
A() { std::cout << 1; }
A(int) { std::cout << 7; }
~A() { std::cout << 5; }
};
struct B {
B() { std::cout << 2; }
B(int) { std::cout << 9; }
~B() {std::cout << 3;}
};
struct C {
B b;
A a1;
A a2;
C() : a1(3){
b = 3;
a2 = 7;
}
};
int main(){
C c;
return 0;
}
输出如下:
B() A(int) A() B(int) ~B() A(int) ~A() ~A() ~A() ~B()
2 7 1 9 3 7 5 5 5 3
我的猜测是,在 b = 3 和 a2 = 7 行上,3 和 7 必须隐式转换为 B 和 A,当它们被复制到 b 和 a2 时,它们会被销毁。
这是正确的还是这里发生了其他事情?
回答
您没有记录复制构造函数和复制赋值运算符,例如:
struct A {
A() { ... }
A(int) { ... }
A(const A&) { ... } // <-- add this
~A() { ... }
A& operator=(const A&) { ...; return *this; } // <-- add this
};
struct B {
B() { ... }
B(int) { ... }
B(const B&) { ... } // <-- add this
~B() { ... }
B& operator=(const B&) { ...; return *this; } // <-- add this
};
但是,如果您实际计算您显示的输出,您会发现您看到的是匹配的构造函数和析构函数。您有 3 个A构造函数调用和 3 个~A析构函数调用。您有 2 个B构造函数调用和 2 个~B析构函数调用。
B() C::b
A(int) C::a1
A() C::a2
B(int) temp
B= temp -> C::b
~B() temp
A(int) temp
A= temp -> C::a2
~A() temp
~A() C::a2
~A() C::a1
~B() C::b
演示
- @Dzamba you ARE seeing the temp objects being destructed. Count the outputs. You have 3 `A` objects being constructed and destructed, and 2 `B` objects being constructed and destructed.