geometrian
geometrian

Reputation: 15387

Reattaching/Removing wxMenu on a wxMenuBar + Memory Concerns

I have a wxMenuBar, and a wxMenu. I can successfully attach the menu to the menubar with Append(...). I can also successfully remove the menu with Remove(...).

The "menu" sample demonstrates adding and removing menus: it creates a menu, Append-s it, and then Remove-s it, calling delete on the returned pointer. To add another, it makes a whole new menu. Thus there's not any reattaching.

However, I would like to be able to Append, Remove, and the re-Append any particular menu (or something equivalent that allows that). Furthermore, it must have no memory leaks.


I have tried:

//startup
menubar->Append(menu,title);
//later
delete menubar->Remove(1);

That produces a working program with no memory leaks. Curiously, I have found that the pointer returned by menubar->Remove isn't the same as the pointer originally Append-ed.

I tried:

//startup
menubar->Append(menu,title);
//later
delete menubar->Remove(1);
menubar->Append(menu,title); //add it back immediately after removing it.

This produces an assertion error in appbase.cpp:1015, something about attaching a menu twice.

I don't really know what I'm doing, and I would appreciate if someone would explain the "right" way to do this.

Upvotes: 0

Views: 710

Answers (2)

ravenspoint
ravenspoint

Reputation: 20462

So long as you do not delete the menu and keep it saved somewhere, you should be fine.

Something like this:

//construct menu
// this needs to be saved somewhere, perhaps as an attribute of the app frame 
wxMenu * menu = new wxMenu( title );
....

// Attach menu to menubar
menubar->Append(menu,title);

....

// remove menu ( but don't delete! )
menubar->Remove(1);

....

// re-attach menu
Append(menu,title);

This is standard way to handle pop-up context menus that are shown when something is right-clicked, except that instead of popping up the menu in the window, it is attached to the menubar.

Upvotes: 1

VZ.
VZ.

Reputation: 22688

I don't understand how can the menu returned by Remove() be different from the one you appended. Perhaps your menu is not at the position 1?

Anyhow, the rules are simple: menu bar takes ownership of the menus appended to (or inserted into) it, meaning that it will delete them. When you remove a menu from the menu bar, it relinquishes ownership and now you're responsible for deleting it.

So you can remove the menu and add it back again later. But you can't add the same menu twice.

Upvotes: 1

Related Questions