Appendix A. The RefPtr smartpointer

Table of Contents

Glib::RefPtr is a smartpointer. Specifically, it is a reference-counting smartpointer. You might be familiar with std::auto_ptr<>, std::unique_ptr<> and std::shared_ptr<>, which are also smartpointers. Glib::RefPtr<> is similar to std::shared_ptr<>, which is also reference-counting. Glib::RefPtr<> was introduced long before there was a reference-counting smartpointer in the C++ Standard Library.

Reference

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

Copying

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

Glib::RefPtr<Gdk::Pixbuf> refPixbuf = Gdk::Pixbuf::create_from_file(filename);
Glib::RefPtr<Gdk::Pixbuf> refPixbuf2 = refPixbuf;

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

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