Despite bummi's fine explanation of why Image1.Picture := nil
won't cause a memory leak, I'm concerned that it may raise red-flags in the minds of new people reading my code, since its safety is counter-intuitive. Therefore, I'd like to avoid it. What more-intuitive alternatives exist? Although bummi's answer was for Delphi, I'm actually more interested in C++Builder.
-
1This is a general problem with Properties: you don't know what hooks are in place . If the syntax were `Image1.setPicture(NULL);` then there'd be no confusion. – M.M Aug 24 '14 at 13:01
4 Answers
The alternative is to use Image->Picture->Assign(NULL);
, which is actually what Image->Picture = NULL;
does internally.

- 555,201
- 31
- 458
- 770
I've set Image1.Visible
to false
to cause a picture to disappear.
- Disadvantage: You'll have to restore
Visible
totrue
when you want to display the next image. - Advantage: if you happen to want to display one particular image, but only at certain times, then toggling Visible could be more efficient than clearing and reloading.

- 424
- 4
- 14
If you're worried that the reader doesn't understand what image.Picture := nil;
means, and you've established that that is the most straightforward way to clear an image, then add a comment stating what the property setter does.
I don't necessarily agree that it needs any change at all, though. It's well-established that property setters can have side effects, and there is no convention in Delphi that after setting a property to a specific value, that re-reading that property will return that same value. In fact, in the VCL I suspect that properties that don't return the same value that was just set are more common.
Either way, comment or not, I would leave the assignment using nil
exactly as it is.
Encapsulating the property assignment provides two advantages:
- a single location to document the non-leakiness of it (DRY)
- a less worrisome-looking interface to use everywhere else
e.g.:
// Not a memory leak: see http://stackoverflow.com/a/23999207/782738
#define ClearImage(Image) Image->Picture = NULL

- 424
- 4
- 14