Marus Gradinaru
Marus Gradinaru

Reputation: 3110

When I load a new image in a TBitmap I must destroy the existing one first?

I am loading multiple images from resources in a TImageList at runtime with this code:

 Bitmap:=TBitmap.Create;
 MyIcons:=TImageList.Create(self);
 Bitmap.LoadFromResourceName(HInstance,'DEFAULT16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.LoadFromResourceName(HInstance,'FOLDER16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.LoadFromResourceName(HInstance,'BACK16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.Free;

I want to know if I should destroy the previous bitmap (Bitmap.Assign(nil)) when I load a new one or this is done automatically in LoadFromResourceName method. I mean I don't want to have memory leakage...

Upvotes: 2

Views: 857

Answers (1)

David Heffernan
David Heffernan

Reputation: 613382

No. When LoadFromResourceName executes, it clears any memory and resources used by the previous image, and loads the new one.

Your code is fine, modulo the missing try/finally. It should be:

Bitmap := TBitmap.Create;
try
  ....
finally
  Bitmap.Free;
end;

Without that, should an exception be raised in between assigning to Bitmap, and destroying the object, the object would not be destroyed and would be leaked.

Upvotes: 4

Related Questions