Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

wxWidgets and exception safety, i.e. std::bad_alloc

10 views
Skip to first unread message

Krzysiek Czaiński "Czajnik"

unread,
Jun 7, 2009, 1:21:37 PM6/7/09
to
I'm wondering, how wxWidgets treats exception safety. The last
discussion I found about it is quite old, so I think it's worth to
reopen the subject.

For example:
###
wxFrame* f = ...;
wxMenuBar* menuBar = new wxMenuBar;
wxMenu* menu = new wxMenu;
menu->Append( ID_1, _("Item1") );
funCall();
menuBar->Append( menu, _("&Menu1") );
f->SetMenuBar( menuBar );
###

The above code is clearly NOT exception-safe.
1. An std::bad_alloc may be thrown during allocation of menu, and that
would leak menuBar.
2. funCall() could throw anything, and that would leak menu and
menuBar.
3. Somthing else could throw, i.e. evaluation of wxString( _
("Item1") ) -- or could it?

To come up with an exception-safe solution, one might try to use a
smart pointer. My proposition is to only reorganize the above code:

###
wxFrame* f = ...;
wxMenuBar* menuBar = new wxMenuBar;
f->SetMenuBar( menuBar ); // frame takes ownership right after
allocation
{
funCall(); // may throw
wxString title( _("&Menu1") ); // create wxString before
allocating wxMenu
wxMenu* menu = new wxMenu;
// now, since the wxString was created earlier,
// nothing will be thrown until Append takes ownership of menu
menuBar->Append( menu, title );
menu->Append( ID_1, _("Item1") );
}
###

My questions are:
A. Do wxWidgets operations throw std::bad_alloc, or anything, or what
happens in an out-of-memory situation? If wxWidgets doesn't throw,
will it throw in future versions? I hope yes ;-)
B. Is my proposition above really exception safe? If so, is there a
nicer exception-safe solution?

0 new messages