-
class deleting itself
Code:
#include <iostream>
using namespace std;
class Foo
{
public:
void Destroy();
} *global_foo;
void Foo::Destroy()
{
delete global_foo;
cout << "Still here..." << endl;
}
int main()
{
global_foo = new Foo;
global_foo->Destroy();
return 0;
}
What should happen when I run this? Because it runs without errors, but I'm not sure wether it's valid to do this. I mean, shouldn't the object be deleted after "delete global_foo"? Which means "Still here..." shouldn't be displayed right? But it is. Any possible side effects I should know of?
-
Nothing is going wrong. The fact that you deleted global_foo is still true, but you can print as many messages as you want. It has nothing to do with freeing the memory that global_foo points to.
-
I think what you wrote is fine and legal because the object is only needed to call the function: not to do what's inside it.
-
This is basically this. I mean. Haha.
http://www.parashift.com/c++-faq-lit...html#faq-16.15
[16.15] Is it legal (and moral) for a member function to say delete this?