#include <iostream>
using namespace std;
namespace GB
{
class Test
{
public:
Test() { cout << "Constructor is executed\n"; }
~Test() {
cout << i << " " << "Destructor is executed\n";
this->i = 7;
}
int i = -1;
};
}
int main()
{
// Test(); // Explicit call to constructor
GB::Test t; // local object
t.i = 6;
t.~Test(); // Explicit call to destructor
return 0;
}
输出
Constructor is executed
6 Destructor is executed
6 Destructor is executed
我的问题是:
1) 为什么析构函数会被调用两次。
2) 在第一次调用析构函数时,成员变量的值从6更改为7,但在第二次调用中它仍然是6。
3) 我们能够停止析构函数的第二次调用吗?(我只想手动调用析构函数)。
this->i = 7;
没有任何效果,因为那是最后一次可以合法访问this
。对i
的更改无法被观察到。编译器完全可以正确地将其优化掉。 - François Andrieux