I have a question on proper coding practice. I have written two classes, texture and bitmap. A texture has a bitmap member (a pointer named m_Bitmap). Because a Bitmap has resources that must be managed (dynamically allocated memory), if I create a Texture which creates a Bitmap, and then later copy some other Texture into my original Texture, I have to clean up the Bitmap I created before. So I've written a Copy method that both the copy constructor and the assignment operator will call.
The question is, should I explicitly clean up the Bitmap in Texture::Copy:
void Texture::Copy(const Texture& newTexture)
{
if(m_Bitmap != NULL)
{
delete m_Bitmap;
m_Bitmap = NULL;
}
m_Bitmap = new Bitmap(newTexture.m_Bitmap);
}
Should I do it in Bitmap::Copy:
Bitmap::~Bitmap()
{
Delete();
}
void Bitmap::Delete()
{
if(m_Data == NULL)
return;
for(int i = 0; i < m_Width; i++)
delete [] m_Data;
delete m_Data;
m_data = NULL;
}
void Bitmap::Copy(const Bitmap& newBitmap)
{
Delete();
}
void Texture::Copy(const Texture& newTexture)
{
m_Bitmap = new Bitmap(newTexture.m_Bitmap);
}
Or should I do both:
Bitmap::~Bitmap()
{
Delete();
}
void Bitmap::Delete()
{
if(m_Data == NULL)
return;
for(int i = 0; i < m_Width; i++)
delete [] m_Data;
delete m_Data;
m_Data = NULL;
}
void Bitmap::Copy(const Bitmap& newBitmap)
{
Delete();
}
void Texture::Copy(const Texture& newTexture)
{
if(m_Bitmap == NULL)
{
delete m_Bitmap;
m_Bitmap = NULL;
}
m_Bitmap = new Bitmap(newTexture.m_Bitmap);
}
Now I believe all of those will get the job done (I just typed them here and now so there may be a typo or something I didn't think of), and the last solution is particularly redundant. However I actually think it might be the best solution, as it combines the safety of the Bitmap's copy cleaning up the resources (so if anyone forgets to do so when making such a copy it still gets done), as well as clearly expresses its intent to clean up the bitmap's resources before re-assigning the pointer.
So which, if any, of these solutions is the proper way to go about handling a situation like this?
Also, is this:
delete m_Bitmap;
m_Bitmap = NULL;
redundant? Does delete set m_Bitmap to NULL automatically? I've always just done it myself.
Without order nothing can exist - without chaos nothing can evolve.