Advertisement

Q: delete for an object?

Started by July 02, 2000 11:09 AM
3 comments, last by Cobalt 24 years, 5 months ago
Hi there, I have what I think is a pretty simple question. It may even be slightly stupid on my part If I create an object using "myClass *ob = new myClass() ;", then how do I put in delete? Do I call delete just like "delete ob", or do I need to put something like "delete this" in the destructor ~myClass() and wait for the object to go away by itself? Or should I do both, call "delete ob;" and have something like "delete this;" in the destructor also? None of my books explain this, and I really want to do it the "right way" TM... Okay, thank ya''ll much...
Don''t try to delete the object in the destructor. Let''s say you do something like this:

main()
{
myClass ob;
// Calls the destructor and tries to destroy self, but doesn''t work...
}

Your program will probably crash. Don''t put the delete in the destructor.

main()
{
myClass *ob = new myClass() ;
delete ob;
}

- Muzzafarath

Mad House Software
The Field Marshals
I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, "What is that, swearing?" - Larry Wall
Advertisement
Destructors work whenever an object is deallocated. delete deallocates objects, so if you call "delete this;" in the destructor then you have a problem.

In almost all cases, you simply call delete on the pointer (in the example, it would be "delete ob;"). "delete this;" is really only useful inside a member function that is not a destructor.

Good Luck!




- null_pointer
Sabre Multimedia
Thanks, just what I wanted to know!
Also, it''s considered good to always assign a pointer to NULL (or 0) after you delete it. That way you''ll get an easy to follow error rather than upredictable resultes if you try to dereference it after it''s been deleted.

This topic is closed to new replies.

Advertisement