Boost logo

Boost Users :

From: Simon Pickles (sipickles_at_[hidden])
Date: 2008-07-12 07:14:12


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::vector<boost::any> many

// CCore.cpp snippet

        boost::function<bool(many&)> cb =
m_eventHandler->RegisterGUICallback( boost::bind(
&IGUIInterface::HandleEventMessage, m_gui, _1 ) );

        m_gui->RegisterEventHandler( cb );

// CEventHandler.cpp snippet
// boost::function<bool(many&) m_guiTx declared in .h

boost::function<bool(many&)>
CEventHandler::RegisterGUICallback(boost::function<bool(many&)> f)
{
    // MEM LEAK IS HERE - A circular reference?
    m_guiTx = f;
   
    return boost::bind(&CEventHandler::HandleGUIRx, this, _1);
}

// CGUI.cpp snippet
// boost::function<bool(many&) eventHandlerCallback declared in .h

void CGUI::RegisterEventHandler( boost::function<bool(many&)> 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


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net