Hello,
I am using boost::functions to provide a simple event system, but have
come across a problem.
I have two classes that need to communicate with each other, CGUI and
CEventHandler. Their instances are both shred_ptrs owned by a third
class, CCore.
To establish comms, I am passing boost::functions which have been bound
to members of the two classes:
//---------------------
typedef std::vectorboost::any many
// CCore.cpp snippet
boost::function cb =
m_eventHandler->RegisterGUICallback( boost::bind(
&IGUIInterface::HandleEventMessage, m_gui, _1 ) );
m_gui->RegisterEventHandler( cb );
// CEventHandler.cpp snippet
// boost::function
CEventHandler::RegisterGUICallback(boost::function f)
{
// MEM LEAK IS HERE - A circular reference?
m_guiTx = f;
return boost::bind(&CEventHandler::HandleGUIRx, this, _1);
}
// CGUI.cpp snippet
// boost::function cb )
{
m_eventHandlerCallback = cb;
m_log->GUI("EventHandler callback registered. Testing...\n");//, s );
std::string message = "This was sent from CGUI::RegisterEventHandler\n";
int id = 43;
many msg;
boost::any _message = message;
boost::any _id = id;
msg.push_back(_id);
msg.push_back(_message);
m_eventHandlerCallback(msg);
}
//-----------------------------------------------------
As you can see, CCore binds a public member function of m_gui and passes
it to the eventhandler, where it is stored and used to send events.
The event handler returns its own member function, bound to this, which
CCore duly passes to m_gui.
Now both classes hold objects with refs to each other, and the program
does a big memory dump when it is ended, on win32 with MSVC2005. I
envisage this is because the shared_ptrs holding the instances of CGUI
and CEvenHandler are not destructing at program close.
Commenting out the line:
m_guiTx = f;
eliminates the issue.
What is a better way to achieve this?
Thanks
Simon