我有以下简单代码:
class A
{
int a;
public:
A(int a) : a(a) { cout << "Constructor a=" << a << endl; }
~A() { cout << "Destructor a=" << a << endl; }
void print() { cout << "Print a=" << a << endl; }
};
void f()
{
A a(1);
a.print();
a = A(2);
a.print();
}
int main()
{
f();
return 0;
}
输出是:
Constructor a=1
Print a=1
Constructor a=2
Destructor a=2
Print a=2
Destructor a=2
我发现 a=2
有两个析构函数调用,a=1
没有一个析构函数调用,而每种情况都有一个构造函数调用。那么在这种情况下如何调用构造函数和析构函数呢?
最佳答案
a = A(2);
将使用默认的 operator=
为 a
赋新值,将其 a::a
成员值设置为 2。
void f()
{
A a(1);//a created with int constructor a.a == 1
a.print();// print with a.a == 1
a = A(2);//Another A created with int constructor setting a.a == 2 and immediately assigning that object to a
//object created with A(2) deleted printing 2 it was created with
a.print();//a.a==2 after assign
}//a deleted printing 2 it was assigned with
您可能应该阅读 Rule of three以便更好地了解正在发生的事情。
关于c++ - 堆栈上的构造函数/析构函数调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129917/