I’ve previously managed to store a boost::bind function in a variable, allowing me to call the function as needed at a later time. It’s pretty straightforward, you simply do something like this:
//Caller, note the Accepthandler function is specified here
mysocket->RegisterAcceptHandler(boost::bind(&AcceptHandler,_1,_2));
//Registration function, a member of the socket class. cnctCallBack is a typedef to a boost:function
void mynamespace::socket::RegisterAcceptHandler( const cnctCallBack &cb )
{
connectCallBack = cb;
}
and call connectCallBack as you like with appropriate arguments.
My problem is that I now want the handler to register the function in an inner member object. In other words, socket will no longer be calling the callback, but an inner class will be told about the callback, and it will call it. You’d think that you could simply assign the &cb to a function in the inner class, but it turns out not to be so:
typedef boost::function<void()> recCB;
class InnerClass{
public:
void AttachListener(const recCB &rcb);
void RunListener();
private:
boost::function<void()> callback;
};
void InnerClass::AttachListener( const boost::function<void()> &rcb )
{
callback = rcb;
}
void InnerClass::RunListener()
{
callback();
}
class OuterClass{
public:
void AttachListener(const boost::function<void()> &rcb);
void RunListener();
private:
InnerClass * ic;
boost::function<void()> cb;
};
void OuterClass::AttachListener( const boost::function<void()> &rcb )
{
cb = rcb;
ic->AttachListener(rcb);
}
void OuterClass::RunListener()
{
cb();
ic->RunListener();
}
It turns out when I run the outerclass and try to assign a function using OuterClass.AttachListener, it gives me an access violation at 0xfffff…, which is a rather conspicuous address. Looking at the call stack, something about the assignment operator is causing the problem, but I can’t see what the problem is. It is easy enough to check that the same assignment code works when assigning to a variable in the outer class. I wonder if there’s something about the *this that means you can only do this in one level.
icis a pointer, and I don’t see anywhere you have allocated memory for it. That is the reason why you get access-violation error at runtime.Well, that doesn’t mean that you go and allocate memory to it. I would rather suggest you to declare
icas follows:which is a non-pointer member, and use it as:
That is much better.