elm*_*rki 7 c++ constructor destructor
我有以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码的输出是2020。我想会发生什么,创建了一个临时对象a。一旦使用赋值运算符将值赋值为 20,就会调用析构函数并打印 20。然后 main 函数到达 return 并再次调用析构函数,再次打印 20。
我对吗?
小智 3
你是对的。实际上将你的代码修改如下可以更清晰地展示代码的逻辑。
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
调用构造函数!
调用构造函数!
20
20
| 归档时间: |
|
| 查看次数: |
199 次 |
| 最近记录: |