-
Destruction
Regarding destructors, does it work the same as a constructor whereby if you define part of it yourself then the default is ignored and only what you write is initialised?
so is there a chance of a memory leak if i say have an object containing some big arrays as well as image surfaces and then in the destructor i only explicitly free the memory for the surfaces?
or will everything be freed anyway?
-
If you don't write any code to explicitly do something, then of course it won't just happen automagically. That's why RAII is so important - by delegating the task to a "smart" object, you generally don't have to write much "clean-up" code in your destructors.
-
The destructor of every object in the class will of course be called in the default destructor. However, as you should know, there is no destructor for built-in types such as pointers, hence they will not release the memory they hold.
And since there is only one destructor (a destructor cannot take any parameters), it's either the default or your own.
So you must explicitly call delete in your destructor to free any pointers, or alternatively use a smart pointer whose destructor will release any pointer it holds.
-
Just thought I'd add that in inheritance heirarchies, the destructor of any base classes will always be called. The one exception is that if you allocate a derived object to a base-class pointer, and then delete the latter, the chain of destructors will only be called if the base class declares it's destructor as virtual, so be sure to do that always, obviously.
-
cheers, i checked up on a mailing list article in response to your replies, its got plenty of good stuff about 'auto' freeing memory, in the present application i think that i can keep track easy enough and will be sure, now that i know to write all the cleanup stuff in, one thing i did spot in the article was a link to exception handling and it says if you wrap the program in a try...catch.... does this mean that in my case with an events driven loop in main() i can wrap that in a try.. catch and direct exceptions for handling, for everything?
-
For the general case, yes, you can do that. In some situations, though, you'll want to handle certain exceptions elsewhere in the program's logic. It just depends, really.