Alternatively, you can let a widget's container control when the widget is
destroyed. In most cases, you want a widget to last only as long as the
container it is in. To delegate the management of a widget's lifetime to its
container, first create it with manage() and
pack it into its container with add(). Now, the
widget will be destroyed whenever its container is destroyed.
Dynamic allocation with manage() and add()
gtkmm provides the manage() and add() methods to create and destroy widgets.
Every widget except a top-level window must be added or packed into a container in
order to be displayed. The manage() function marks a packed widget so that when the
widget is added to a container, the container becomes responsible for deleting the
widget.
MyWidget::MyWidget()
{
Gtk::Button* pButton = manage(new Gtk::Button("Test"));
add(*pButton); //add aButton to MyWidget
}
Now, when MyWidget is destroyed, the button will also be deleted. It is no
longer necessary to delete pButton to free the button's memory; its deletion
has been delegated to MyWidget.
gtkmm also provides the set_dynamic() method for all widgets.
set_dynamic() can be used to generate the same result as manage(), but
is more tedious:
foo.add( (w=new Gtk::Label("Hello"), w->set_dynamic(), &w) );
is the same as
foo.add( manage(new Gtk::Label("Hello")) );
Of course, a top level container will not be added to another container. The
programmer is responsible for destroying the top level container using one of
the traditional C++ techniques. For instance, your top-level Window might just be an instance in your main() function..