为什么输出是2020?
Why is the output 2020?
我有以下代码:
#include <iostream>
using namespace std;
class Foo {
int data;
public:
Foo(int d = 0) {
data = d;
}
~Foo() {
cout << data;
}
};
int main() {
Foo a;
a = 20;
return 0;
}
这段代码的输出是 2020。我想发生的事情是,创建了一个临时对象 a。一旦使用赋值运算符为 a 赋值 20,就会调用析构函数并打印 20。然后 main 函数到达 return 并第二次调用析构函数,再次打印 20.
我说得对吗?
你是对的。
其实修改你的代码如下可以更清楚的展示代码的逻辑。
#include <iostream>
using namespace std;
class Foo {
int data;
public:
Foo(int d = 0) {
cout << "call constructor!" << endl;
data = d;
}
~Foo() {
cout << data << endl;
}
};
int main() {
Foo a; // Foo::Foo(int d = 0) is called which yields the first line of output
a = 20; // is equal to follows
// 1. a temporary object is constructed which yields the second line of output
Foo tmp(20);
// 2. since you do not provide operator= member function,
// the default one is generated the compiler
// and a member-wise copy is performed
a.operator=(&tmp);
// after this copy assignment, a.data == 20
// 3. tmp is destroyed which yields the third line of output
tmp.~Foo();
// 4. right before the program exits, a is destroyed which yields the last line of output
a.~Foo();
return 0;
}
输出为:
call constructor!
call constructor!
20
20
我有以下代码:
#include <iostream>
using namespace std;
class Foo {
int data;
public:
Foo(int d = 0) {
data = d;
}
~Foo() {
cout << data;
}
};
int main() {
Foo a;
a = 20;
return 0;
}
这段代码的输出是 2020。我想发生的事情是,创建了一个临时对象 a。一旦使用赋值运算符为 a 赋值 20,就会调用析构函数并打印 20。然后 main 函数到达 return 并第二次调用析构函数,再次打印 20.
我说得对吗?
你是对的。 其实修改你的代码如下可以更清楚的展示代码的逻辑。
#include <iostream>
using namespace std;
class Foo {
int data;
public:
Foo(int d = 0) {
cout << "call constructor!" << endl;
data = d;
}
~Foo() {
cout << data << endl;
}
};
int main() {
Foo a; // Foo::Foo(int d = 0) is called which yields the first line of output
a = 20; // is equal to follows
// 1. a temporary object is constructed which yields the second line of output
Foo tmp(20);
// 2. since you do not provide operator= member function,
// the default one is generated the compiler
// and a member-wise copy is performed
a.operator=(&tmp);
// after this copy assignment, a.data == 20
// 3. tmp is destroyed which yields the third line of output
tmp.~Foo();
// 4. right before the program exits, a is destroyed which yields the last line of output
a.~Foo();
return 0;
}
输出为:
call constructor!
call constructor!
20
20