Page 1 of 1

Freeing memory

Posted: Mon Aug 16, 2010 6:37 pm
by Trimmy
Hey, is it best to free dynamic memory in a class's destructor or in a member function?
Example:

Code: Select all

SomeClass::~SomeClass( void ) {
delete a;
delete [] b;
}
// or
void SomeClass::cleanUp( void ) {
delete a;
delete [] b;
}
Does it not matter ( obviously other than the fact the member function will have to be called )? Does it depend on the situation? Should the cleanUp function be called the destructor? Thanks for any help in advance and I hope this isn't an absolute noob question.

Re: Freeing memory

Posted: Mon Aug 16, 2010 6:43 pm
by X Abstract X
Assuming that the dynamically allocated memory needs to remain allocated for the lifetime of the object, it should be freed in the destructor, that's what destructors are for.

Re: Freeing memory

Posted: Mon Aug 16, 2010 7:00 pm
by Trimmy
X Abstract X wrote:Assuming that the dynamically allocated memory needs to remain allocated for the lifetime of the object, it should be freed in the destructor, that's what destructors are for.
Yeah thats what I thought but I wasn't sure, thanks.