Murray's Blog

C++ in Glom: shared_ptr and slots/functions

I’m playing more with C++11 in g++ (Use –std=c++11), this time with Glom.


Glom has a custom reference-counted shared pointer, Glom::sharedptr, which seems to work well, but I was glad to replace it with std::shared_ptr so I never have to wonder if it’s working properly. Krzesimir showed that I could make it a little more concise by using std::make_shared(). I’ll use auto some time to make it even neater. For instance, make_shared() takes the parameters to the constructor of the class:

auto some_thing = std::make_shared<SomeThing>(1, 2, 3);

It’s a lot like glibmm’s Glib::RefPtr, though that lets GObject do the reference-counting, so one day glibmm/gtkmm will have similar changes.


glibmm still uses sigc::slot with sigc::signal, but I had some application code that used its own slots as callbacks. So I changed these from sigc::slot to std::function. The new syntax doesn’t feel quite as nice. For instance:

Replacing sigc::slot declarations with std::function

std::function uses a slightly different syntax than sigc::slot for declaring its functors:

sigc::slot<void, int, int> some_slot;

would now be this, which I guess is OK:

std::function<void(int, int)> some_slot;

Using non-member functions

sigc::ptr_fun() has no equivalent, so this:

std::slot<void> some_slot = std:ptr_fun(&some_non_member_func);


std::function<void()> some_slot = &some_non_member_func;

though that same syntax is legal with libsigc++ too. The & is optional when getting function pointers in C or C++, but I like it.

Using member functions

sigc::mem_fun() has no equivalent either. std::mem_fn() just gives you the member function without associating an instance, so you need to use std::bind() to get both. So, this:

std::slot<void> some_slot = sigc::mem_fun(*this, &SomeThing::some_method);


std::function<void()> some_slot = std::bind(&SomeThing::some_method, this);

That becomes particularly awkward if your member method takes any parameters, because std::bind() expects you to supply all parameter values when using std::bind(), not just when calling the slot/function later. std::placeholders::_* is the awkward way to work around this (thanks again to Krzesimir). So:

std::slot<void, int, int> some_slot = sigc::mem_fun(*this, &SomeThing::some_method);


std::function<void(int, int)> some_slot = std::bind(&SomeThing::some_method, this, std::placeholders::_1, std::placeholders::_2);

Presumably this simplifies the implementation, but the result is that the common case is less readable. Still, I’d be glad to have one less library (libsigc++) to think about if we can ever replace sigc::slot with std::function in glibmm and gtkmm. However, C++11 does not yet have any equivalent for sigc::signal so we’ll still need libsigc++ for a while.

Exit mobile version