Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to destroy icon after I added it to ImageList?

I'm loading my icons using LoadIconWithScaleDown API (or using LoadImage for XP.) I then add it to my CImageList as such:

//CImageList imgList;
//HICON hIcon = loaded with LoadIconWithScaleDown
imgList.Add(hIcon);

//Is the following line needed?
::DestroyIcon(hIcon);

I see contradicting statements about whether or not I should free the icon after it's added to my image list.

The documentation for CImageList::Add says:

You are responsible for releasing the icon handle when you are done with it.

But the documentation for ImageList_ReplaceIcon that CImageList::Add calls internally says:

You do not need to destroy hicon if it was loaded by the LoadIcon function; the system automatically frees an icon resource when it is no longer needed.

Well, I did not exactly load it with LoadIcon (which is deprecated.) So what shall I do?

like image 553
c00000fd Avatar asked Jun 15 '14 07:06

c00000fd


1 Answers

No function related to image lists will ever destroy an icon automatically. That is because the owner of the icon needs to decide whether or not to destroy it. This information can be found in the documentation for DestroyIcon where you are told not to use DestroyIcon with shared icons:

It is only necessary to call DestroyIcon for icons and cursors created with the following functions: CreateIconFromResourceEx (if called without the LR_SHARED flag), CreateIconIndirect, and CopyIcon. Do not use this function to destroy a shared icon. A shared icon is valid as long as the module from which it was loaded remains in memory. The following functions obtain a shared icon.

  • LoadIcon
  • LoadImage (if you use the LR_SHARED flag)
  • CopyImage (if you use the LR_COPYRETURNORG flag and the hImage parameter is a shared icon)
  • CreateIconFromResource
  • CreateIconFromResourceEx (if you use the LR_SHARED flag)

This effectively puts the onus on the application programmer to keep track of whether or not DestroyIcon is needed. And so other API functions simply will never call DestroyIcon.

The documentation from ImageList_ReplaceIcon that you refer to is simply repeating the advice that I quote above.

Image lists don't actually hold icons. They hold rectangular bitmaps with the images tiled. So they make a copy of the image that you provide. As a general rule, an API function will never require you to keep a parameter alive after the function returns without that requirement being explicitly documented. And what's more, such a requirement would be onerous on the caller, and a good API would never put such a requirement on the caller if it can be readily avoided.

like image 55
David Heffernan Avatar answered Sep 25 '22 14:09

David Heffernan