I have not played c ++ for a long time and I have forgotten so much that maybe the doubt I have or the possible failure is really something basic in the language.
I have written a small code to test the overhead of the delete operator in c ++ with a virtual destructor and I have found that it only works correctly the first time you call delete.
The code is here (it's a page that allows you to write code online and execute it, I've tried it in visual studio and gcc and it's exactly the same thing): link
Could someone tell me why this is happening? Only the first time works well and the second one is not working well
I put the code here also and the result it gives:
#include <stdio.h>
class Base
{
public:
virtual ~Base() { printf("~Base\r\n"); }
void operator delete(void *m) { printf("delete Base\r\n"); }
};
class Derived : public Base
{
public:
Derived() { x = 1; }
~Derived() { printf("~Derived\r\n"); }
void operator delete(void *m) { printf("delete Derived\r\n"); }
int x;
};
int main()
{
Derived *derived = new Derived();
printf("1) delete derived (%i)\r\n", ((Derived*)derived)->x);
delete derived;
printf("2) delete derived (%i)\r\n", ((Derived*)derived)->x);
delete derived;
return 0;
}
Result:
1) delete derived (1)
~Derived
~Base
delete Derived
2) delete derived (1)
~Base
delete Base
Now, if we remove the "virtual" class called "Base" everything is perfect, logically whenever we call the delete with "Derived" (the code is ready to remove the virtual and nothing fails). To run it: link
Thanks