Question: Are there special precautions needed, when passing around instance member functions?
Scenario: Sporadic crashes when I pass around and call an instance member function.
- The member function is called constantly (hundreds of thousands of times) via the function pointer.
- The process eventually crashes, but the stack trace is somewhat inconsistent. The only common denominator seems to be that new/malloc fails, even though there's plenty of process memory available.
- To the best of my knowledge the instance (CClass in the example below) is still alive.
- The member function can have an empty body; simply trying to call that method via the function pointer is enough to corrupt the heap (assuming it's heap corruption).
- Single-threaded, single-process.
- This is visual studio 6.0 on XP.
Note: To side-step the issue, I made CFunctor a friend of CClass and give it access CClass members; but I'd like to know if my original approach was flawed from the get-go.
A simplified example:
class CFunctor
{
private:
    typedef void (CClass::*Calculator)(args);
    CClass *c;
    Calculator func;
public:
    CFunctor(CClass* c, Calculator func)
    {
        this->c = c;
        this->func = func;
    };
    ~CFunctor()
    {
        this->c = NULL;
        this->func = NULL;
    }
    virtual void calculate(args)
    {
        (c->*func)(args);
    }
};
class CFunctorConsumer
{
public:
    CFunctorConsumer(CFunctor *functor)
    {
        this->functor = functor;
    }
    ~CFunctorConsumer()
    {
        this->functor = NULL;
    }
    virtual void DoStuff(args)
    {
       if (this->functor)
       {
           this->functor->calculate(args);
       }
    }
private:
    CFunctor *functor;
}
class CClass
{
private:
    CFunctorConsumer* testFunctor;
    void CalculationMethod(args)
    {
       // This method can be empty, and still crashes
    }
public:
    CClass()
    {
        this->testFunctor = new CFunctorConsumer(new CFunctor(this, this->CalculationMethod));
    }
    void Test()
    {
       this->testFunctor->DoStuff( args );
    }   
}
 
     
     
    