Lifetime of an object

Hi,

This is probably a bit stupid question, but I think I’m missing something and I’m not sure what is it.

I’m trying to write a simple app, the main looks as follows:

fn main() -> glib::ExitCode {
    let application = gtk::Application::new(
        Some("MySuperApp"),
        Default::default(),
    );
    application.connect_activate(build_ui);
    application.run()
}

The thing I’m missing happens in build_ui

pub fn build_ui(application: &gtk::Application) {
    ...
//this is my custom object that uses Vec, so I figured Rc<RefCell<>> is a way to go here
 let mut register = Rc::new(RefCell::new(Register::new()));

//now I want to use register in 2 handlers in a mut way

    //here
    hex_entry.connect_activate(clone!(@strong register => move |entry| {
           //some code
          register.borrow_mut()
    }

    //and here
    open_button.connect_clicked(glib::clone!(@weak register => move |_| {
        //some code
        register.borrow_mut();
    }

What I don’t understand is why my app only works if one of the references is @strong.
I know that Rc counts references every time clone() is invoked, however my register object doesn’t implement that trait. Is @strong keeping it somehow “alive” ?

I know this is very basic stuff, but if someone could explain what am I missing here I’d grateful.

Please check the documentation about how reference counting, weak vs. strong references work for details. For example the documentation of std::rc or for the general concepts Wikipedia about reference counting and weak references.

In short: if there’s no strong reference to a value anymore then it’s freed. So if you only have two weak references that are passed to the closures, the value will be freed more or less immediately when the original strong reference (Rc::new()) goes out of scope.

Thanks for the clarification Sebastian.

I think that I have a basic understanding of strong/weak references. I suspect that I’m missing some context specific to gtk-rs.

As I understand build_ui binds signals handlers with GObjects events like button click.
Since GObject’s have a static lifetime and are reference counted I suspect why they don’t out of the scope.

The thing I’m struggling to understand is how to assure a correct lifetime of my custom struct. Shall I move it out of the build_ui function or there is some good pattern I could use?

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.