Jump to content
  • Advertisement
Sign in to follow this  
pex22

C++: 'delete this' (not the topic)

This topic is 4886 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

Can I do:
struct A
{
~A() {delete this;}
};
A a; // global object
And be sure that a will be deleted from memory in the end of program? thanks, pex.

Share this post


Link to post
Share on other sites
Advertisement
Bad plan. When you get to ~A, 'this' is already in the process of being deleted. Not to mention, it's a global object, so you shouldn't be using the delete operator on it at all.


class A { ~A() {delete this; } }
A* pA = new A; delete pA;


Will give you either an immediate crash or an infinite loop.

If it's a global object (that isn't a pointer) it will be cleaned up automatically after main() exits.

Share this post


Link to post
Share on other sites
Oh, I didn't knew that on global objects. I thought they aren't deleted automatically like global variables (in C, i don't know about C++. Are the global vars deleted automatically in C++ in the end of the program too?).
Thanks [smile]

pex.

Share this post


Link to post
Share on other sites
Basically objects (not allocated using new/new[]) are deleted and memory associated with them is freed when they go out of scope. So:

{
Thing x;
do_stuff_with(x);
}

x is deleted at the }

Globals work pretty much the same way - they're created when your program starts up and destroyed when it exits. Unfortunately you can end up with some rather peculiar problems when things MUST be created in a specific order (there are solutions to this), since the order of creation is not defined between different .cpp files. You may even accidently create a situation where A's constructor needs B and B's constructor needs A :)

Keep in mind that with pointers, destroying the pointer does not destroy whatever it's pointing to, unless you use an appropriate type of 'smart' pointer.

Share this post


Link to post
Share on other sites
If you new it, delete it.
If you malloc it, free it.
...

If you didn't create the object through a call to the OS, or the new keyword, then you have no deletion to do for it either. It's as simple as that.

Share this post


Link to post
Share on other sites
And if you new[] it, delete[] it. And if you mix them up, the gods of C++ karma will watch quietly for a while, then give you a nice big smack.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!