|
Boost : |
From: graham.shanks_at_[hidden]
Date: 2002-10-14 12:35:23
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));
Assuming that my analysis is correct, might I suggest than the
documentation be extended to:
a) add a comment in the Connection Management section of signalN to
state that a copy is made of the slot (or should this be that it is
unspecified if a copy of the slot is made?)
b) Add an example to the tutorial pointing out this behaviour (you may
freely use the example above)
Might I further suggest that mention is made of the observer pattern
in the introduction to the library - many programmers are more
familiar with that terminology than signals & slots.
I also found it surprising that the copy was nested to a depth of 7,
but that may just be a consequence of the compiler I'm using (MSVC 6.0
SP5).
BTW thanks Doug for a great library. I'm busy replacing my own
observer classes with the signal library - which will finally allow me
to replace my home-brewed callback library with boost::function.
Graham Shanks
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk