Archived

This topic is now archived and is closed to further replies.

destroying an instance of a class explicitley

This topic is 5581 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

class Foo{
     Foo() { cout << "constructor" << endl; }    
     ~Foo() { cout << "destructor" << endl; }    

     void Suicide(){
        delete this;    
     }
}
 
is this the proper way to get rid of my class instance and free up my resources? what if i want to create my object w/out using the new keyword? Does it make sense to call the destructor explicitley? i have like 5 c++ books, none of which cover this topic in detail. any ideas?

Share this post


Link to post
Share on other sites
Yup, as you pointed out that only works if the class was allocated with new, so Suicide will crash if you call it with a global/stack variable.

Try making the constructor private, and put a static method in which returns a new instance. This is the class factory pattern.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Share this post


Link to post
Share on other sites