I am considering using the boost library to design a simple yet effective callback event notification framework for my game application. The idea is that objects that can raise events would have a signal exposed via some public interface. Objects that are interested can connect to the signal and when signal needs to be raised, a boost function gets created, sent to the event queue and later invoked as a callback to raise the signal.
class Transform {
public:
//! Signal
boost::signals2::signal<void(Vector3&)> TransformChangedEvent;
void SetPosition(const Vector3& newPosition) {
mPosition = newPosition;
GetEventSystem()->Queue(boost::bind(boost::ref(TransformChangedEvent), newPosition));
};
class EventSystem {
typedef std::vector<SignalCallback> EventQueue;
EventQueue mQueue;
public:
typedef boost::function<void()> SignalCallback;
void Queue(EventSystem::SignalCallback callback) {
mQueue.push_back(callback);
}
void Dispatch(void) {
while(!mQueue.empty()) {
SignalCallback& f = mQueue.front();
mQueue.erase(mQueue.begin());
f();
}
}
};
//! somewhere object of interest would do this
void Callback(Vector3& pos) { std::cout << "Position changed to " << pos << "\n"; }
mTransform.TransformChangedEvent.connect(boost::bind(&Callback, _1));
This is a very over-simplified implementation. I realize if I don't wrap my arguments being packaged into the boost::bind() call, they'll be copied several times before the actual function is passed to the Queue method for storage.
Should I wrap all my arguments in boost::ref() as well or would that present issues in the above example if I did when the variable leaves scope?
And lastly would there be a better implementation to accomplish the same affect?