I have a piece of code where I can call destructor multiple times and access member functions even the destructor was called with member variables' values preserved. I was still able to access member functions after I called delete but the member variables were nullified (all to 0). And I can't double delete. Please kindly explain this. Thanks.
#include <iostream>
using namespace std;
template <typename T>
void destroy(T* ptr)
{
ptr->~T();
}
class Testing
{
public:
Testing() : test(20)
{
}
~Testing()
{
printf("Testing is being killed!\n");
}
int getTest() const
{
return test;
}
private:
int test;
};
int main()
{
Testing *t = new Testing();
cout << "t->getTest() = " << t->getTest() << endl;
destroy(t);
cout << "t->getTest() = " << t->getTest() << endl;
t->~Testing();
cout << "t->getTest() = " << t->getTest() << endl;
delete t;
cout << "t->getTest() = " << t->getTest() << endl;
destroy(t);
cout << "t->getTest() = " << t->getTest() << endl;
t->~Testing();
cout << "t->getTest() = " << t->getTest() << endl;
//delete t; // <======== Don't do it! Double free/delete!
cout << "t->getTest() = " << t->getTest() << endl;
return 0;
}