I am trying to figure out in C++ the difference between delete operator and destructor and I tried use the following two snippets (I use visual studio 2019 to compile them) :
code 1:
#include <stdio.h>
class A
{
public:
A() { a = new int; *a = 42; b = 33; }
~A()
{
printf("destructor!\n");
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);
//delete myA;
myA->~A();
printf("b:%d\n", myA->b);
printf("a:%d\n", *(myA->a));
}
code2: (almost the same with code 1, just change use delete to use desctructor)
#include <stdio.h>
class A
{
public:
A() { a = new int; *a = 42; b = 33; }
~A()
{
printf("destructor!\n");
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);
delete myA;
//myA->~A();
printf("b:%d\n", myA->b);
printf("a:%d\n", *(myA->a));
}
while running code 2 throws exception:
,
and the console is :
From the results I guess that when you run myA->~A(), it just execute the destructor defined, that is delete a, making this pointer a dangling pointer. when you run delete myA, it not will also execute destructor, and make pointer myA a dangling pointer. But I am not sure how exactly these are implemented.
The explanation of the difference of the two results is my first question
The second question is: the code snippet is copied from Here, and its result is also different from mine, hopefully if anyone can also explain this