Shared resources
| Chapter 25. Memory management |

## Shared resources

Some objects, such as `Gdk::Pixbuf`s and `Pango::Font`s, are obtained from a shared store. Therefore you cannot instantiate your own instances. These classes typically inherit from `Glib::Object`. Rather than requiring you to reference and unreference these objects, gtkmm uses the `Glib::RefPtr<>` smartpointer. Cairomm has its own smartpointer, `Cairo::RefPtr<>`.

Objects such as `Gdk::Pixbuf` can only be instantiated with a `create()` function. For instance,

    auto pixbuf = Gdk::Pixbuf::create_from_file(filename);

You have no way of getting a bare `Gdk::Pixbuf`. In the example, `pixbuf` is a smart pointer, so you can do this, much like a normal pointer:

    auto width = 0;
    if(pixbuf)
    {
      width = pixbuf->get_width();
    }

When `pixbuf` goes out of scope an `unref()` will happen in the background and you don't need to worry about it anymore. There's no `new` so there's no `delete`.

If you copy a `RefPtr`, for instance

    auto pixbuf2 = pixbuf;

or if you pass it as a method argument or a return type, then `RefPtr` will do any necessary referencing to ensure that the instance will not be destroyed until the last `RefPtr` has gone out of scope.

See the appendix for detailed information about RefPtr.

If you wish to learn more about smartpointers, you might look in these books:

- Bjarne Stroustrup, "The C++ Programming Language" Fourth Edition - section 34.3

- Nicolai M. Josuttis, "The C++ Standard Library" - section 4.2

Chapter 25. Memory management |  | Chapter 26. Gtk::Builder