Boost: boost::bind calling multiple times the object destructor

In my previous article C++: Les signaux facile (fr) I explain how to use sigc or boost to connect methods together and fire signals.

But I’m not covering the case when you wants to use signals to connect object instance methods.

I created a Github repository boost-signal-example where I pushed a project demonstrating the described process.

Connect object instance methods together

Signal creation

In this example, there is an object A that expose a signal signalUserCreated and that signal pass the reference of a User object containing all the new user information.

The B object wants to be notified when a new user is created.

In the class_a.h file:

And in the class_a.cpp file:

Signal is now ready so that all other objects can use the connect method to subscribe to that signal.

Signal connection

Now let’s see how to connect objects methods together.

In our main file we will first instantiate both objects, then call the connect method from the ClassA object in order to connect the ClassB::on_new_user method.
Based on my previous article on the signals, the connect is as the following:

In the main.cpp file:

Objects are now well connected and we can now start to have more fun! :-)

Fire the signal!

We now need a method in ClassA that will fire the signal:

In the class_a.cpp file:

So we create a new user with received parameters and then send a reference of this new user to all subscribed objects.

Finally the only thing that remains is to call the ClassA::create_new_user method from the main.cpp file:

Then in the terminal you should see the following output:

ClassA::ClassA
ClassB::ClassB
ClassA::connect
ClassA::create_new_user
ClassB::on_new_user
A new user named Guillaume who is 29 has been created in ClassA.
ClassB::~ClassB
ClassA::~ClassA

You can find the entire code into my new Github repository boost-signal-example.

boost::bind is calling multiple time the object destructor

In the case the object ClassB destructor is called multiple times, and so generate this kind of output:

ClassA::ClassA
ClassB::ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassA::connect
ClassB::~ClassB
ClassB::~ClassB
ClassB::~ClassB
ClassA::create_new_user
ClassB::on_new_user
A new user named Guillaume who is 29 has been created in ClassA.
ClassB::~ClassB
ClassA::~ClassA
ClassB::~ClassB

It means that you didn’t well connected your objects together as you did this:

but you must do this (notice the additional &):