Boost logo

Boost :

From: Dirk Gerrits (dirk_at_[hidden])
Date: 2002-10-14 14:44:29


graham.shanks_at_[hidden] wrote:
> I found the following behaviour in boost::signal rather surprising
>
> struct EventCounter
> {
> EventCounter() : events(0) {}
> void operator()() { events++; }
> int events;
> };
>
> boost::signal0<void> sig;
> EventCounter eventCounter;
> sig.connect(eventCounter);
> sig();
> std::cout << "Events: " << eventCounter.events << std::endl;
>
> gave the output
>
> Events: 0
>
> instead of the expected 1.
>
> On investigation the reason is that the "eventCounter" slot is copied
> and the signal emitted to the copy (presumably this is the reason why
> slot must be copy constructable).
>
> The solution to get the expected (by me) behaviour is to use
> boost::bind, i.e.
>
> sig.connect(boost::bind(&EventCounter::operator(), &eventCounter));

I'd use this:

sig.connect( boost::ref(eventCounter) );

That way, a reference to your original object should get connected instead of a
copy, so the output of your test program should be 1.

I didn't run this through a compiler so please forgive me if I made a typo or
other mistake. ;)

Dirk Gerrits


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk