Sign in to follow this  
Hollower

boost::signals::trackable and user-defined functors

Recommended Posts

According to the tutorial at boost.org boost::signals::trackable only works with function objects created by boost::bind, and not user-defined functors. Is this still true? I ask because it appears to work in my test code. I need to connect signals to functors stored in a dynamic container. When these elements are destroyed, any connected signals must disconnect from them. The container actually stores shared_ptrs so copying doesn't leave things dangling. Here is the test code:
#include <iostream>
#include <vector>
#include <boost/signals.hpp>
#include <boost/smart_ptr.hpp>

struct Slot : public boost::signals::trackable
{
	int n;
	Slot(int n) : n(n) {}
	void operator()() { std::cout << "Slot " << n << " called." << std::endl; }
};

int main()
{
	boost::signal<void ()> sig;

	typedef boost::shared_ptr<Slot> slot_ptr;
	std::vector< slot_ptr > slots;

	slots.push_back( slot_ptr(new Slot(1)) );
	sig.connect( *(slots.back())  );
	slots.push_back( slot_ptr(new Slot(2)) );
	sig.connect( *(slots.back())  );
	slots.push_back( slot_ptr(new Slot(3)) );
	sig.connect( *(slots.back())  );
	sig();
	slots.clear();
	sig();
}

Output:
Slot 1 called.
Slot 2 called.
Slot 3 called.

So, is this safe to work with? I'm not worried about multithreaded right now since the docs say Boost::Signals isn't thread-safe anyway.

Share this post


Link to post
Share on other sites
Quote:
Original post by Hollower
So, is this safe to work with? I'm not worried about multithreaded right now since the docs say Boost::Signals isn't thread-safe anyway.


It should be fine as far as I know. I believe they only mean user-defined function objects that do not implement trackable. I may be wrong, though.

By the way, a thread-safe version of signals is available in the Boost Vault. I haven't tried using it yet, though.

jfl.

Share this post


Link to post
Share on other sites
After looking at trackable_test.cpp I think I finally understand what they're saying. A trackable doesn't have to be a function object at all, and you can use boost::bind to bind a trackable to another function which doesn't know about trackables. In my test they are already bound because the this pointer for operator() points to a trackable. [totally]

Thanks!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this