I'm puzzled by the ownership of submenus. According to tools like
BoundsChecker and Memory Validator, my simple code excerpt below has a
resource leak. On the other hand, the MFC documentation clearly says that
the main menu will take care of destroying the added submenu. A shell
namespace extension needs to do lots of things with menus and I don't want
to leave any resource leaks there.
Code sample:
// Create the main menu.
CMenu menuMain;
menuMain.CreateMenu();
// Create a submenu.
CMenu menuSub;
menuSub.CreatePopupMenu();
menuSub.AppendMenu( MF_STRING, ID_APP_EXIT, ( LPCTSTR )"Exit" );
// Add the submenu to the main menu.
menuMain.AppendMenu( MF_POPUP, ( UINT )menuSub.m_hMenu, "File" );
menuSub.Detach(); // Comment out this line to avoid the leak reports.
Quote from MSDN / CMenu::AppendMenu:
"When nIDNewItem specifies a pop-up menu, it becomes part of the menu to
which it is appended. If that menu is destroyed, the appended menu will also
be destroyed. An appended menu should be detached from a CMenu object to
avoid conflict."
But BoundsChecker and Memory Validator both say that the menu resource
created by the menuSub.CreatePopupMenu() call is not getting destroyed.
The destructor of the CMenu class calls DestroyMenu for the HMENU handle of
menuMain. But is the submenu destroyed as well? According to MSDN it is, but
BoundsChecker and Memory Validator claim otherwise. What is the truth?
(The issue is not MFC-specific. It can easily be reproduced with pure Win32
API calls.)
Antti Nivala