Appendix A. The RefPtr smartpointer

# Appendix A. The RefPtr smartpointer

`Glib::RefPtr` is a smartpointer. Specifically, it is a reference-counting smartpointer. You might be familiar with `std::unique_ptr<>` and `std::shared_ptr<>`, which are also smartpointers. In gtkmm-4.0 `Glib::RefPtr<>` is an alias for `std::shared_ptr<>`, which is reference-counting. `Glib::RefPtr<>` was introduced long before there was a reference-counting smartpointer in the C++ Standard Library.

If you make your own `Glib::ObjectBase`-derived classes with `create()` methods that return a `Glib::RefPtr`, you must use `Glib::make_refptr_for_instance()` in your `create()` methods. This function creates a `std::shared_ptr` with a special deleter, which handles the reference-count for the wrapped C object.

`Glib::RefPtr` is not used for storing widgets derived from `Gtk::Widget`. Widgets have public constructors instead of protected constructors and `create()` methods.

Reference

A smartpointer acts much like a normal pointer. Here are a few examples.

## Copying

You can copy `RefPtr`s, just like normal pointers. But unlike normal pointers, you don't need to worry about deleting the underlying instance.

    auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
    auto refPixbuf2 = refPixbuf;

Of course this means that you can store `RefPtr`s in standard containers, such as `std::vector` or `std::list`.

    std::list<Glib::RefPtr<Gdk::Pixbuf>> listPixbufs;
    auto refPixbuf = Gdk::Pixbuf::create_from_file(filename);
    listPixbufs.push_back(refPixbuf);

Chapter 32. Contributing |  | Dereferencing