I'm experimenting with calling an object's destructor explicitly. The following code works as expected:
class Foo {
public:
~Foo() {
x_=x_+10;
std::cout << "x_ = " << x_ << std::endl;
}
int x() {
return x_;
}
int x_=0;
};
int main()
{
Foo f;
std::cout << "f.x() = " << f.x() << std::endl;
f.~Foo();
f.~Foo();
std::cout << "f.x() = " << f.x() << std::endl;
return 0;
}
And the printout is:
f.x() = 0
x_ = 10
x_ = 20
f.x() = 20
x_ = 30
As expected, every time the destructor is called, x_ is incremented by 10, so we see the progression from 10 to 20 to 30.
However, if we remove the std::cout
from the destructor, such as the following:
class Foo {
public:
~Foo() {
x_=x_+10;
}
int x() {
return x_;
}
int x_=0;
};
int main()
{
Foo f;
std::cout << "f.x() = " << f.x() << std::endl;
f.~Foo();
f.~Foo();
std::cout << "f.x() = " << f.x() << std::endl;
return 0;
}
Then the printout becomes:
f.x() = 0
f.x() = 0
The increment in the destructor no longer works. Can someone explain why the behavior of the destructor can be affected by a print statement?