Recently I have noticed some of my objects become quite large and after a while I might not need them any longer. I could wait until the end of the local scope for the destructor to release the memory or use custom scopes using code blocks.
However, I had this idea to implement, for each object, a void MyObject::clear()
method that clears the memory:
class MyObject{
bool is_cleared;
// Other stuff
public:
MyObject();
~MyObject();
void clear();
// Other stuff
};
MyObject::MyObject()
: is_cleared(false)
{
// construct the class
}
void MyObject::clear(){
if (!is_cleared){
// clear memory
is_cleared = true;
}
}
MyObject::~MyObject(){
this->clear();
}
This way I can either let the destructor clear the memory or do it myself. Is this considered a good or bad practice? How can I improve it?