构造函数和析构函数调用的顺序?
我无法理解构造函数和析构函数调用的顺序?该语句A b = f(a)首先执行什么?有人可以帮我吗?
I cannot understand the order of constructor and destructor calls? What will execute first in this statement A b=f(a)? Can someone please help me out?
#include<iostream>
using namespace std;
class A {
int x;
public:
A(int val = 0)
:x(val) {
cout << "A " << x << endl << flush;
}
A(const A& a) {
x = a.x;
cout << "B " << x << endl << flush;
}
void SetX(int x) {
this->x = x;
}
~A() {
cout << "D " << x << endl << flush;
}
};
A f(A a) {
cout << " C " << endl << flush;
a.SetX(100);
return a;
}
int main()
{
A a(1);
A b=f(a);
b.SetX(-100);
return 0;
}
输出窗口:
A 1
B 1
C
B 100
D 100
D -100
D 1
为什么在输出窗口的第2行中打印B 1?
Why does it print B 1 in line 2 of the output window?
为什么在第2行中打印B 1?"
因为从此语句中调用了复制构造函数
Because the copy constructor was called from this statement
A b=f(a);
函数 f()
要求通过值传递 A
,因此在函数调用堆栈上为此参数创建了一个副本.
The function f()
requires A
being passed by value, thus a copy for this parameter is made on the function call stack.
如果您的下一个问题是如何克服这种行为,并避免调用复制构造函数,则可以简单地将 A
实例作为对 f()的引用
:
If your next question should be, how you can get over this behavior, and avoid to call the copy constructor, you can simply pass the A
instance as a reference to f()
:
A& f(A& a) {
// ^ ^
cout << " C " << endl << flush;
a.SetX(100);
return a;
}
附带说明: endl<<flush;
是多余的BTW, std :: endl
已包含刷新.
Side note: endl << flush;
is redundant BTW, std::endl
includes flushing already.