Good style for memory management?



Hi,

I am new to gtk/gtkmm. I have some basic questions about
memory management which I was not able to look up from
the list / manual.

If I am trying to keep the widgets that I do not need
to access after having specified the layout, I end up
putting them on the heap.

FindDlg::FindDlg()
{

    Gtk::VBox* vbox(Gtk::manage(new Gtk::VBox));
    // ...
    // ...
    add(*vbox);
}

Fine, just that no function between new and add must throw,
or I am getting leaks.

Next attempt:

class FindDlg : public Gtk::Window
{
    public:
        FindDlg();
        virtual ~FindDlg();
    protected:
        // the next both widgets need to be
        // accessed during lifetime of FindDlg
        Gtk::ComboBoxEntryText m_find;
        Gtk::FileChooserButton m_file;
};

FindDlg::FindDlg()
{
    set_default_size(500,500);

    // create local widgets, and put them into auto_ptr
    // and mark them as managed
    std::auto_ptr<Gtk::VBox> vbox(Gtk::manage(new Gtk::VBox));
    std::auto_ptr<Gtk::HBox> query(Gtk::manage(new Gtk::HBox));
    std::auto_ptr<Gtk::Label> findpat(Gtk::manage(new Gtk::Label));
    std::auto_ptr<Gtk::Label> results(Gtk::manage(new Gtk::Label));

    // adjust the widgets and set data
    findpat->set_label("File find pattern:");
    findpat->set_alignment(Gtk::ALIGN_LEFT);
    results->set_label("Search results:");
    results->set_alignment(Gtk::ALIGN_LEFT);
    vbox->set_border_width(10);

    // hand off the widgets to their containers
    // take care, not to access a widget after release
    vbox->pack_start(*findpat.release(), Gtk::PACK_SHRINK);
    query->pack_start(m_find,Gtk::PACK_EXPAND_WIDGET);
    query->pack_end(m_file,Gtk::PACK_SHRINK);
    vbox->pack_start(*query.release(),Gtk::PACK_SHRINK);

    vbox->pack_start(*results.release(), Gtk::PACK_SHRINK);
    add(*vbox.release());

    show_all_children();
}


FindDlg::~FindDlg()
{
}

This code looks very "noisy" and fragile to me. Are there any
recommendations to do better? In particular I am interested
in comments about better style of memory management.

Thank you,
speedsnail





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]