Deleting an instance of a class [C++]

Started by
6 comments, last by Valere 14 years, 8 months ago
I feel this is a pretty noobish question, but oh well. How do I destroy an instance of a class in C++?
Advertisement
That depends on how you created it.

On the stack:
{    MyClass myInstance;    // use instance here} // all stack objects are destroyed here automatically

On the heap with a raw pointer:
MyClass * my_raw_ptr = new MyClass;// use instance heredelete my_raw_ptr; // delete the instance

On the heap with a stack-allocated smart pointer:
{    boost::shared_ptr<MyClass> my_smart_ptr( new MyClass );    // use instance here} // all stack objects are destroyed, the smart pointer therefore dies  // and automagically deletes your heap instance too... unless you made  // copies of it, in which case it will be deleted once all the copied  // pointers are destroyed (or made to point to something else)
Mmmh I see, I knew about that delete command, but what I really wanted to know is how to destroy the instance of a class, inside a member function.

Thanks for the help so far. :)
Quote:Original post by MikeDee
Mmmh I see, I knew about that delete command, but what I really wanted to know is how to destroy the instance of a class, inside a member function.


It's extremely rare that one needs to do that. Usually it's a rather dangerous thing to do as the object probably doesn't know where it is. For example if I call x.destroy() where x is an object in an STL container, it won't get removed from that container. You're left with an object that has been torn down, but the container doesn't know that and assumes all the same invariants still hold.

If you can absolutely guarantee that your object is allocated in the free store (the "heap") with the new operator, then you can "delete this;" inside a member function. This is also somewhat rare and again can be dangerous as it may create one or more dangling pointers.

In short, there's probably a much better way to achieve your goal. What are you trying to do?
Hmm, you don't really. It's all about the scope of an object's lifetime.

For stack-allocated objects they generally live from the moment they're constructed till their scope block terminates (usually with a closing backet, often a curly brace), you never manually destroy them.

For heap-allocated objects referenced via a raw pointer you do manually destroy them and unlike stack objects they persist past the end of the scope block in which in they were created, right up until you delete them. You can delete a heap-allocated instance anytime you want so this is really the closest thing to what you're asking for, as far as I can tell.

For heap-allocated objects that are passed to a smart pointer you don't delete them, you let the smart pointer take care of it. It'll delete an instance whenever there are no more smart pointers left pointing at the thing. The smart pointers themselves are stack-allocated so they will be destroyed when their scope block ends. By keeping a careful control over what you do with your smart pointers, and resetting/nulling them when appropriate, you can essentially control when a smart pointer will destroy an instance this gives you a similar (but safer!) level of control that a raw pointer with delete would.

It is possible to destroy instances in exotic ways, at times that would usually be unexpected, but such things are dangerous and only used for very low-level memory management stuff - the kind of thing that goes on in the deep, dank, dark depths of a std::vector to squeeze every ounce of performance out of it. People don't usually do that kind of thing themselves.
Is this something like what you are trying to do?

void Foo::Bar(){    Baz b;    // do some things with b    int i = b.GetSomeInterestingNumber();    // &lt;-- destroy b here for some good reason    Qux q;    q.DoSomething(i);}


If so, create a local scope by using { and }.

void Foo::Bar(){   int i = DEFAULT_INTERESTING_NUMBER;   {      Baz b;      // do some things with b      i = b.GetSomeInterestingNumber();   } // b is destroyed here when it goes out of scope   Qux q;   q.DoSomething(i);} // q destroyed here when it goes out of scope.


It's probably possible (and a good idea) to redesign your code so that each local block is a function call, but this can be useful when testing out ideas.
Quote:Original post by MikeDee
Mmmh I see, I knew about that delete command, but what I really wanted to know is how to destroy the instance of a class, inside a member function.


The same instance of the same class whose member function is active?

I can almost guarantee that you don't really need or want to do this, even in the case where it's safe. Could you show some of the code context where you want to do this and explain where and why?

But... if you're 100% sure the object has been allocated with 'new', and you're 100% sure that the function cannot possibly look at or touch anything in the class, directly or indirectly, after the point where you want to destroy it, you can 'delete this'. Which should have occurred to you; after all, you know about 'delete', and you can't really have gotten this far without knowing that 'this' is a pointer to the current object?
The C++ FAQ lite talks about "delete this".

Summary: In some extremely specific circumstances with objects you have total control over, it's okay.

MFC uses "delete this" in the management of View classes, which virtually guarantees that just about everyone will write something that crashes before they work out what is going on.

This topic is closed to new replies.

Advertisement