I know about the delete operator and how it automatically calls the destructor of a class. However, I've recently seen someone call the destructor of a class directly, which seemed quite strange to me. So I wrote short program that gives a really un-expected result:
#include <stdio.h>
class A
{
public:
A() {a = new int; *a=42; b=33;}
~A() {delete a;}
int* a;
int b;
};
int main(int argc, const char ** argv)
{
A* myA = new A();
printf("a:%d b:%d\n", *(myA->a), myA->b);
myA->~A();
printf("b:%d\n", myA->b);
printf("a:%d\n", *(myA->a));
}
So as you see, I'm calling the destructor ~A(), so to my expectation the program should crash when trying to access the variable 'a' a second time (because it was deleted 2 lines ago). Instead.. the program just prints this without any complaints:
a:42 b:33
b:33
a:42
... Why? What happens exactly when I call ~A() directly? Is there any situation when it's useful to do so?