I have a function Foo and a class CDelegate.
typedef void (*typeFctPtr)(void*);
void Foo(void* dummy)
{
cout << "Foo\n";
}
class CDelegate
{
public:
CDelegate (const typeFctPtr& f_ref_Wrapper, void* f_pvSubscriber)
: m_ref_Wrapper(f_ref_Wrapper), m_pvSubscriber(f_pvSubscriber)
{
}
inline void operator () () const
{
(*m_ref_Wrapper)(0);
}
inline void operator=(const CInterruptDelegate& D)
{
}
private:
void* m_pvSubscriber;
const typeFctPtr& m_ref_Wrapper;
};
A second class has a static member static CDelegate m_Delegate; which I initialize using the constructor like this:
CInterruptDelegate CSpi1::m_Delegate(FreeFunction, 0);
I want to call Foo by calling the ()operator of my static object: CSpi1::m_Delegate();
I get an exception at (*m_ref_Wrapper)(0);
Is there something wrong with the syntax? I am not quite sure if what I try to do is possible at all. I have a working solution where the constructor of CDelegatedoes not take a const reference of a function pointer but the function pointer itself. I can then call the function in the ()operator without problems. I want to use a const reference because the function pointer call cannot be optimized and I hope the call via the const reference can because everything should be known at compile time.
You’re holding a reference to a pointer to a function (and the pointer is a temporary which has been destroyed by the time you use it, so things go badly wrong).
Try changing your typedef to be a function type:
Then with your existing code you’ll end up with a reference to a function, and you’ll be fine. Or you could store a pointer to the function –
const typeFct *.And in either case the call can just be
m_ref_Wrapper(0).In general I prefer to typedef function types rather than pointer-to or reference-to, if only because the syntax is less ugly.