bergentroll
bergentroll

Reputation: 127

gtkmm: what is Glib::RefPtr usecases?

I am writing a little GTK3 app with C++ and gtkmm library.

In the gtkmm documentation usually some concrete instances such as Gtk::Application, Gtk::Builder, Gtk::StatusIcon etc. initialized with create() static methods that return a Glib::RefPtr. Meanwhile child widgets usually arise just on stack.

That is not clear for me:

Upvotes: 0

Views: 2453

Answers (2)

  • Is it because memory stack usage or something else? There is no RefPtr's in my code for now. I checked usage of stack with valgrind's massif tool, peak usage was about 100 KB. Seems not too low for me, but comparable size [example with RefPtr's][1] takes a same piece of stack memory.

The main reason is that gtkmm is a thin C++ wrapper over Gtk+ library written in C. Most objects in Gtk+ are allocated on heap (eg. GtkApplication object is created using gtk_application_new function), and are reference counted (manually, using g_object_ref/g_object_unref functions). In other words, those objects have already shared pointer semantics, albeit expressed in plain C. Because of this, it makes most sense to represent those objects in C++ as smart pointers - Glib::RefPtr in this case.

  • May I place all instances just on stack like Application myapp, or should I always use create() while it present?

No, because Gtk::Application contructors are protected, so compiler won't allow to create those objects on stack.

  • What advantages the pointers provide in this case?

I think it's the other way round. Keeping those objects on stack wouldn't provide any advantages, as Gtk objects wrapped by gtkmm objects are essentially shared pointers.

Upvotes: 1

metal
metal

Reputation: 6332

Glib::RefPtr is a reference-counted smart pointer that predates std::shared_ptr and performs the same essential functions. The use case for it is similar -- it allows multiple objects want to share ownership of an object without knowing about each other directly.

In your specific examples, an icon might be shared because it is used in multiple places in a UI, and you don't want to maintain many copies of the same image data, which could use a considerable bit of memory if there are many icons.

The Application and Builder objects are likely held by multiple objects in your program (e.g., different window or dialog objects), so the reference counting keeps each alive as long as one of those objects is still using it. This frees these users of the Application object from having to know about all the other parts of the program that might use the shared Application object. When one window is done with the Application, it destroys its smart pointer to the Application. If that window was the last owner, this also destroys the Application object, but otherwise it stays alive for the other users -- all without your destroyed window knowing about it whether the Application lives on or not.

Upvotes: 2

Related Questions